Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Then parse the jQuery plug-in development

2025-02-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Then analyze the jQuery plug-in development, I believe that many inexperienced people do not know what to do, so this article summarizes the causes of the problem and solutions, through this article I hope you can solve this problem.

There are two kinds of jQuery plug-in development: one is class-level plug-in development, that is, adding new global functions to jQuery, which is equivalent to adding methods to the jQuery class itself. The global functions of jQuery are those that belong to the jQuery namespace, and the other is object-level plug-in development, that is, adding methods to jQuery objects.

1. Class-level plug-in development

The most direct understanding of class-level plug-in development is to add class methods to the jQuery class, which can be understood as adding static methods. A typical example is the $. Ajax () function, which defines the function in the namespace of jQuery. Plug-in development at the class level can be extended in the following forms:

1.1 add a new global function

To add a global function, all we need is the following definition:

Java code

JQuery.foo = function () {alert ('This is a test. This is only a test.');}

1.2 add multiple global functions

To add multiple global functions, you can use the following definition:

Java code

JQuery.foo = function () {alert ('This is a test. This is only a test.');}; jQuery.bar = function (param) {alert (' This function takes a parameter, which is "'+ param +'.');}

The call is the same as for a function: jQuery.foo (); jQuery.bar (); or $.foo (); $.bar ('bar')

1.3 use jQuery.extend (object)

Java code

JQuery.extend ({foo: function () {alert ('This is a test. This is only a test.');}, bar: function (param) {alert (' This function takes a parameter, which is "'+ param +'.);}})

1.4 use namespaces

Although in the jQuery namespace, we prohibit the use of a large number of javaScript function names and variable names. However, it is still inevitable that some function or variable names will conflict with other jQuery plug-ins, so we are used to encapsulating some methods in another custom namespace.

Java code

JQuery.myPlugin = {foo:function () {alert ('This is a test. This is only a test.');}, bar:function (param) {alert ('This function takes a parameter, which is "' + param +'.');}}; the function with the namespace is still a global function, using the method of $.myPlugin.foo (); $.myPlugin.bar ('baz')

With this technique (using separate plug-in names), we can avoid function conflicts in the namespace.

2. Object-level plug-in development

Object-level plug-in development requires two forms:,

Form 1:

Java code

(function ($) {$.fn.extend ({pluginName:function (opt,callback) {/ / Our plugin implementation code goes here. }) (jQuery)

Form 2:

Java code

(function ($) {$. Fn.pluginName = function () {/ / Our plugin implementation code goes here. };) (jQuery)

A jQuery function is defined above, and the parameter is $. After the function definition is completed, pass in the argument jQuery. Call execution immediately. The advantage is that we can also use the alias $when writing jQuery plug-ins without conflicts with prototype.

2.1 declare a name under the JQuery namespace

This is a single plug-in script. If your script contains multiple plug-ins, or reciprocal plug-ins (for example: $.fn.doSomething () and $. Fn.undoSomething ()), then you need to declare multiple function names. However, usually when we write a plug-in, we try to use only one name to contain all its contents. Our sample plug-in is named "highlight"

Java code

Fn.hilight = function () {/ / Our plugin implementation code goes here. Our plug-in is called by: $('# myDiv'). Hilight ()

But what if we need to decompose our implementation code into multiple functions? There are many reasons: design needs; an implementation that is easier or easier to read; and it is more object-oriented. It's a real hassle to break down the functional implementation into multiple functions without adding extra namespaces. To realize that functions are the most basic class objects in javascript, we can do this. Like other objects, functions can be specified as properties. So we have declared "hilight" as the property object of jQuery, and any other properties or functions we need to expose can be declared in the "hilight" function. We'll continue later.

2.2 accept options parameters to control the behavior of the plug-in

Let's add the ability to specify the foreground and background colors for our plug-in. We might let the option be passed to the plug-in function like an options object. For example:

Java code

/ / plugin definition $.fn.hilight = function (options) {var defaults = {foreground: 'red', background:' yellow'}; / / Extend our default options with those provided. Var opts = $.extend (defaults, options); / / Our plugin implementation code goes here. Our plug-in can be called as follows: $('# myDiv') .hilight ({foreground: 'blue'})

2.3 default settings for exposing plug-ins

One improvement we should make to the above code is to expose the default settings of the plug-in. This makes it easier for plug-in users to overwrite and modify plug-ins with less code. Next we start using function objects.

Java code

/ / plugin definition $.fn.hilight = function (options) {/ / Extend our default options with those provided / / Note that the first arg to extend is an empty object-/ this is to keep from overriding our "defaults" object. Var opts = $.extend ({}, $.fn.hilight.defaults, options); / / Our plugin implementation code goes here. }; / / plugin defaults-added as a property on our plugin function $. Fn.hilight.defaults = {foreground: 'red', background:' yellow'}; now users can include a line like this in their script: / / this only needs to be called once, and it is not necessary to call $. Fn.hilight.defaults.foreground = 'blue' in the ready block Next we can use the plug-in method like this, and as a result, it sets the blue foreground color: $('# myDiv'). Hilight ()

Now users can include a line like this in their script:

/ / this only needs to be called once, and does not have to be called in the ready block

$. Fn.hilight.defaults.foreground = 'blue'

Next we can use the plug-in method like this, and as a result, it sets the blue foreground color:

('# myDiv'). Hilight ()

As you can see, we allow users to write a line of code in the default foreground of the plug-in. And users can still optionally override these new default values when needed:

/ / override the default background color of the plug-in

$. Fn.hilight.defaults.foreground = 'blue'

/ /...

/ / invoke the plug-in with a new default setting

$('.hilightDiv'). Hilight ()

/ /...

/ / override the default settings by passing configuration parameters to the plug-in method

('# green') .hilight ({

Foreground: 'green'

});

2.4 properly expose some functions

This section will extend your plug-in step by step to the previous code (and let others extend your plug-in at the same time). For example, our plug-in implementation can define a function called "format" to format highlighted text. Our plug-in now looks like this, and the implementation of the default format method is under the hiligth function.

Java code

/ / plugin definition $.fn.hilight = function (options) {/ / iterate and reformat each matched element return this.each (function () {var $this = $(this); / /. Var markup = $this.html (); / / call our format function markup = $.fn.hilight.format (markup); $this.html (markup);});}; / / define our format function $.fn.hilight.format = function (txt) {return''+ txt +';}

We can easily support other properties in the options object to override the default settings by allowing a callback function. This is another great way to modify your plugin. The technique shown here is to further effectively expose the format function so that it can be redefined. With this technique, others can pass their own settings to override your plug-in, in other words, so that others can also write plug-ins for your plug-in.

Considering the useless plug-ins we built in this article, you may wonder when these will be useful. A real example is the Cycle plug-in. This Cycle plug-in is a slide display plug-in that supports many internal transformations to scroll, slide, gradient disappear, etc. But in practice, there is no way to define the effects that might be applied to each type of sliding change. That's where this extensibility is useful. The Cycle plug-in exposes "transitions" objects to users, causing them to add their own transform definitions. The definition in the plug-in looks like this:

$. Fn.cycle.transitions = {

/ /...

}

This technique allows others to define and pass transformation settings to the Cycle plug-in.

2.5 keep private functions private

This technique is very powerful to expose part of your plug-in to be overwritten. But you need to think carefully about the exposed parts of your implementation. Once exposed, you need to keep any changes to parameters or semantics in mind that may break backward compatibility. A general rule of thumb is that if you are not sure whether to expose a particular function, you may not need to do that.

So how do we define more functions without messing up the namespace or exposing the implementation? This is the function of closures. To demonstrate, we will add another "debug" function to our plug-in. This debug function will output the selected element format to the firebug console. To create a closure, we define the wrapper entire plug-in in a function.

Java code

(function ($) {/ / plugin definition $.fn.hilight = function (options) {debug (this); / /...}; / / private function for debugging function debug ($obj) {if (window.console & & window.console.log) window.console.log ('hilight selection count:' + $obj.size ());} / /...}) (jQuery)

Our "debug" method cannot be entered from an external closure, so it is private to our implementation.

2.6 support for Metadata plug-ins

Based on the plug-in you are writing, adding support for the Metadata plug-in will make it more powerful. Personally, I like this Metadata plugin because it lets you use a few "markup" options to override the plugin (which is very useful when creating examples). And it's very easy to support it. Update: there is a little optimization suggestion in the comments.

Java code

Fn.hilight = function (options) {/ /... / / build main options before element iteration var opts = $.extend ({}, $.fn.hilight.defaults, options); return this.each (function () {var $this = $(this); / / build element specific options var o = $.meta? $.extend ({}, opts, $this.data ()): opts / /...

These change lines do something: it tests whether the Metadata plug-in is installed and if it is installed, it can extend our options object by extracting metadata this line is added to JQuery.extend as a parameter, then it will override any other option settings. Now we can drive the behavior from "markup" if we choose "markup":

When calling, you can write: jQuery.foo (); or $.foo ()

Java code

Have a nice day! Have a nice day! Have a nice day! Now we can highlight which div uses only one line of script: $('hilight'). Hilight ()

2.7 Integration

Here is the code after the completion of our example:

Java code

/ / create a closure (function ($) {/ / definition of the plug-in $.fn.hilight = function (options) {debug (this); / / build main options before element iteration var opts = $.extend ({}, $.fn.hilight.defaults, options) / / iterate and reformat each matched element return this.each (function () {$this = $(this); / / build element specific options var o = $.meta? $.extend ({}, opts, $this.data ()): opts / / update element styles $this.css ({backgroundColor: o.background, color: o.foreground}); var markup = $this.html (); / / call our format function markup = $.fn.hilight.format (markup); $this.html (markup);});} / / Private function: debugging function debug ($obj) {if (window.console & & window.console.log) window.console.log ('hilight selection count:' + $obj.size ());}; / / define expose format function $.fn.hilight.format = function (txt) {return''+ txt +';} / / defaults $.fn.hilight.defaults of the plug-in = {foreground: 'red', background:' yellow'}; / / closure end}) (jQuery)

This design has enabled me to create powerful plug-ins that conform to the specification. I hope it allows you to do the same.

3. Summary

JQuery proposes two methods for developing plug-ins, which are:

JQuery.fn.extend (object); add methods to the jQuery object.

JQuery.extend (object); to extend the jQuery class itself. Add a new method to the class.

3.1 jQuery.fn.extend (object)

What is a fn? It's not hard to find out if you look at the jQuery code.

JQuery.fn = jQuery.prototype = {

Init: function (selector, context) {/ /....

/ /.

}

Originally jQuery.fn = jQuery.prototype. I'm sure I'm no stranger to prototype. Although javascript does not have a clear concept of a class, it is more convenient to understand it with a class. JQuery is a very well-encapsulated class. For example, we use the statement $("# btn1") to generate an instance of the jQuery class.

JQuery.fn.extend (object); an extension to jQuery.prototype is to add "member functions" to the jQuery class. Instances of the jQuery class can use this "member function".

For example, we are going to develop a plug-in and make a special edit box that alert the contents of the current edit box when it is clicked. You can do this:

$.fn.extend ({

AlertWhileClick:function () {

$(this) .click (function () {

Alert ($(this) .val ()

});

}

});

$("# input1"). AlertWhileClick (); / / the page is:

$("# input1") is a jQuery instance. When it calls the member method alertWhileClick, it implements the extension, and each time it is clicked, it will pop up the content in the current edit.

3.2 jQuery.extend (object)

Adding class methods to the jQuery class can be understood as adding static methods. Such as:

$.extend ({add:function (arecom b) {return aforb;}})

Add a "static method" for jQuery as add, which can then be used where jQuery is introduced, $.add (3Magne4); / / return 7

After reading the above, have you mastered and parsed the method of jQuery plug-in development? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report