Topic: full analysis of jQuery plug-in development, jquery plug-in

Source: Internet
Author: User

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"

 

  1. $. Fn. hilight = function (){
  2. // Our plugin implementation code goes here.
  3. };
  4. Our plug-in is called like this:
  5. $ ('# 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:

  1. // Plugin definition
  2. $. Fn. hilight = function (options ){
  3. Var defaults = {
  4. Foreground: 'red ',
  5. Background: 'yellow'
  6. };
  7. // Extend our default options with those provided.
  8. Var opts = $. extend (defaults, options );
  9. // Our plugin implementation code goes here.
  10. };
  11. Our plug-in can be called as follows:
  12. $ ('# MyDiv'). hilight ({
  13. Foreground: 'blue'
  14. });

 

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.

 

  1. // Plugin definition
  2. $. Fn. hilight = function (options ){
  3. // Extend our default options with those provided.
  4. // Note that the first arg to extend is an empty object-
  5. // This is to keep from overriding our "defaults" object.
  6. Var opts = $. extend ({}, $. fn. hilight. defaults, options );
  7. // Our plugin implementation code goes here.
  8. };
  9. // Plugin defaults-added as a property on our plugin function
  10. $. Fn. hilight. defaults = {
  11. Foreground: 'red ',
  12. Background: 'yellow'
  13. };
  14. Now users can include a line like this in their scripts:
  15. // This only needs to be called once and does not have to be called in the ready Block
  16. $. Fn. hilight. defaults. foreground = 'blue ';
  17. Next we can use the plug-in method like this, and it sets the blue foreground color:
  18. $ ('# 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.

 
  1. (Function ($ ){
  2. // Plugin definition
  3. $. Fn. hilight = function (options ){
  4. Debug (this );
  5. //...
  6. };
  7. // Private function for debugging
  8. Function debug ($ obj ){
  9. If (window. console & window. console. log)
  10. Window. console. log ('hilight selection count: '+ $ obj. size ());
  11. };
  12. //...
  13. }) (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.

  1. $. Fn. hilight = function (options ){
  2. //...
  3. // Build main options before element iteration
  4. Var opts = $. extend ({}, $. fn. hilight. defaults, options );
  5. Return this. each (function (){
  6. Var $ this = $ (this );
  7. // Build element specific options
  8. Var o = $. meta? $. Extend ({}, opts, $ this. data (): opts;
  9. //...

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:

  1. // Create a closure
  2. (Function ($ ){
  3. // Plug-in Definition
  4. $. Fn. hilight = function (options ){
  5. Debug (this );
  6. // Build main options before element iteration
  7. Var opts = $. extend ({}, $. fn. hilight. defaults, options );
  8. // Iterate and reformat each matched element
  9. Return this. each (function (){
  10. $ This = $ (this );
  11. // Build element specific options
  12. Var o = $. meta? $. Extend ({}, opts, $ this. data (): opts;
  13. // Update element styles
  14. Export this.css ({
  15. BackgroundColor: o. background,
  16. Color: o. foreground
  17. });
  18. Var markup = javasthis.html ();
  19. // Call our format function
  20. Markup = $. fn. hilight. format (markup );
  21. Export this.html (markup );
  22. });
  23. };
  24. // Private function: debugging
  25. Function debug ($ obj ){
  26. If (window. console & window. console. log)
  27. Window. console. log ('hilight selection count: '+ $ obj. size ());
  28. };
  29. // Define the exposure format Function
  30. $. Fn. hilight. format = function (txt ){
  31. Return '<strong>' + txt + '</strong> ';
  32. };
  33. // Defaults of the plug-in
  34. $. Fn. hilight. defaults = {
  35. Foreground: 'red ',
  36. Background: 'yellow'
  37. };
  38. // Closure ends
  39. }) (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

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.