Topic: full analysis of jQuery plug-in development, jquery plug-in
There are two types of jQuery plug-in development:
One is class-level plug-in development, that is, adding a new global function to jQuery is equivalent to adding a method to the jQuery class itself. JQuery's global functions belong to the jQuery namespace, and the other is object-level plug-in development, that is, adding methods to jQuery objects. The following describes the development of the two functions in detail.
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 is defined in the namespace of jQuery. The following extensions can be used for class-level plug-in development:
1.1Add a new global function
To add a global function, we only need to define it as follows:
1.2Add multiple global functions
Add multiple global functions, which can be defined as follows:
1.3UseJQuery. extend (object );
1.4Use namespace
Although a large number of javaScript function names and variable names are not allowed in the jQuery namespace. But it is still inevitable that some functions or variables will conflict with other jQuery plug-ins, so we are used to encapsulating some methods into another custom namespace.
With this technique (using an independent plug-in name), we can avoid conflicts between functions in the namespace.
2Object-level plug-in development
Object-level plug-in development requires the following two forms :,
Form 1:
Form 2:
2.1InJQueryDeclare a name under the namespace
This is a single plug-in script. If your script contains multiple plug-ins or plug-ins that are mutually inverse (for example, $. fn. doSomething () and $. fn. undoSomething (), you need to declare multiple function names. However, when writing a plug-in, we usually try to use only one name to include all its content. Our example plug-in is named "highlight"
- $. Fn. hilight = function (){
- // Our plugin implementation code goes here.
- };
- Our plug-in is called like this:
- $ ('# MyDiv'). hilight ();
But what if we need to break down our implementation code into multiple functions? There are many reasons: design needs; easier or easier to read implementation; and more in line with object-oriented. This is really a headache. It breaks down the function implementation into multiple functions without adding additional namespaces. To realize that and use functions are the most basic class objects in javascript, we can do this. Like other objects, functions can be specified as attributes. Therefore, we have declared "hilight" as a jQuery attribute object. Any other attribute or function that we need to expose can be declared in the "hilight" function. Continue later.
2.2AcceptOptionsParameters to control the actions of the plug-in
Let's add features for our plug-in to specify the foreground color and background color. We may make options pass to the plug-in function like an options object. For example:
- // 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.3Default settings of the exposure plug-in
One improvement of 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 to use function objects.
- // 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 scripts:
- // 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 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. You can also overwrite these new default values as needed:
// Overwrite the Default background color of the plug-in
$. Fn. hilight. defaults. foreground = 'blue ';
//...
// Call the plug-in using a new default setting
$ ('. HilightDiv'). hilight ();
//...
// Pass the configuration parameters to the plug-in method to overwrite the default settings
$ ('# Green'). hilight ({
Foreground: 'green'
});
2.4Expose some functions as appropriate
This section will expand your plug-ins step by step through interesting methods for the previous Code Section (while allowing others to expand your plug-ins ). For example, we can define a function named "format" in the implementation of the plug-in to format the highlighted text. Our plug-in now looks like this. The implementation of the default format method is under the hiligth function.
$. Fn. cycle. transitions = {
//...
};
This technique allows others to define and pass transformation settings to the Cycle plug-in.
2.5Keep private functions
This technique exposes some of your plug-ins to be overwritten. But you need to think carefully about what is exposed in your implementation. Once exposed, you need to maintain any changes to the parameters or semantics in your mind may undermine backward compatibility. A general principle is that if you are not sure whether to expose a specific function, you may not need to do that.
So how can we define more functions without disrupting namespaces or exposing implementations? This is the function of the closure. For demonstration, 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 entire plug-in as a function.
- (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 enter from external closures, so our implementation is private.
2.6SupportedMetadataPlug-ins
Based on the plug-in you are writing, adding support for the Metadata plug-in can make it more powerful. Personally, I like this Metadata plug-in because it allows you to overwrite the plug-in options with a few "markup" plug-ins (this is useful when creating an example ). It is also very simple to support. Update: There are some optimization suggestions in the comments.
- $. 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 is to test whether the Metadata plug-in is installed. If it is installed, it can expand our options object by extracting the metadata line and adding it to JQuery as the last parameter. extend, it will overwrite any other option settings. Now we can drive behavior from "markup". If we select "markup ":
You can write jQuery. foo (); or $. foo ();
2.7Integration
The code after the example is completed is as follows:
- // Create a closure
- (Function ($ ){
- // Plug-in Definition
- $. 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
- Export this.css ({
- BackgroundColor: o. background,
- Color: o. foreground
- });
- Var markup = javasthis.html ();
- // Call our format function
- Markup = $. fn. hilight. format (markup );
- Export this.html (markup );
- });
- };
- // Private function: debugging
- Function debug ($ obj ){
- If (window. console & window. console. log)
- Window. console. log ('hilight selection count: '+ $ obj. size ());
- };
- // Define the exposure format Function
- $. Fn. hilight. format = function (txt ){
- Return '<strong>' + txt + '</strong> ';
- };
- // Defaults of the plug-in
- $. Fn. hilight. defaults = {
- Foreground: 'red ',
- Background: 'yellow'
- };
- // Closure ends
- }) (JQuery );
This design allows me to create a powerful compliant plug-in. I hope it can also be done for you.
3, Summary
JQuery provides two methods for development plug-ins:
JQuery. fn. extend (object); add a method to the jQuery object.
JQuery. extend (object); adds a new method to the class to extend the jQuery class itself.
3.1 jQuery. fn. extend (object );
What is fn. It is not difficult to see jQuery code.
JQuery. fn = jQuery. prototype = {
Init: function (selector, context ){//....
//......
};
It turns out that jQuery. fn = jQuery. prototype. It is certainly no stranger to prototype. Although javascript does not have a clear concept of a class, it is more convenient to use a class to understand it. JQuery is a well-encapsulated class. For example, we use the statement $ ("# btn1") to generate a jQuery class instance.
JQuery. fn. extend (object); the extension to jQuery. prototype is to add "member functions" to the jQuery class ". JQuery class instances can use this "member function ".
For example, we want to develop a plug-in and create a Special edit box. When it is clicked, the content in the current edit box of alert is displayed. You can do this:
$. Fn. extend ({
AlertWhileClick: function (){
$ (This). click (function (){
Alert ($ (this). val ());
});
}
});
$ ("# Input1"). alertWhileClick (); // <input id = "input1" type = "text"/>
$ ("# Input1") is a jQuery instance. When it calls the member method alertWhileClick, the extension is implemented. When it is clicked, the content in the current edit is displayed.
3.2 jQuery. extend (object );
Add a class method to the jQuery class, which can be understood as adding a static method. For example:
$. Extend ({
Add: function (a, B) {return a + B ;}
});
Add a "static method" for jQuery as add, and then you can use this method at the place where jQuery is introduced. $. add (3, 4); // return 7