jquery Plugin Development structure

Source: Internet
Author: User
Tags anonymous bind extend

1, start

You can write a jquery plugin by adding a new function to Jquery.fn. The name of the property is the name of your plugin:

    JQuery.fn.myPlugin = function () {  
        //start writing your code.  
    };  

But where did the endearing dollar sign go. She is jquery, but to make sure that your plugin and other uses go away. She is J Q u e r y, but in order to make sure that your plugin and other uses go away. She's jquery, but to make sure your plug-in doesn't conflict with other libraries you use, it's best to use an anonymous function that is immediately executed, with the parameters of this anonymous function being jquery, so that the other libraries can safely use the $ symbol.

(function ($) {  
      $.fn.myplugin = function () {  

        //start bar.  

      };  
    }) (JQuery)

That would be better. Within the closure, you can safely use the $ symbol ~
2, Context

Now we can write our code, but before I write, I have to say the context. Within the scope of the plug-in, the This keyword points to a jquery object. It is easy to misunderstand this, as this usually points to a DOM element when using jquery normally. Do not understand this, will often use $ and wrapped again.

(function ($) {  

      $.fn.myplugin = function () {  

        //No need to use $ (this)  

        //$ (this) is the  

        same as $ ($ (' #element ')) This.fadein (' normal ', function () {  

          //This here refers to a DOM element  

        });}  

      )  
    (jQuery);  

    $ (' #element '). Myplugin ();  

3, Basic development

(function ($) {  

      $.fn.maxheight = function () {  

        var max = 0;  

        This.each (function () {  
          max = Math.max (max, $ (this). Height ());  
        });  

        return max;  
      };  
    }) (JQuery);  
var tallest = $ (' div '). MaxHeight ();

This is a simple plug-in that returns the height of the maximum div on the page by calling height ().
4, maintain the characteristics of chain-type development

The previous example returns an integer, but in most cases a plugin tightly modifies the collected elements and returns the element to the next use on the chain. This is the beauty of jquery design and one of the reasons why jquery is so popular. In order to guarantee the chain, you must return this.

(function ($) {  

      $.fn.lockdimensions = function (type) {    

        return This.each (function () {  

          var $this = $ (this); 
  if (!type | | type = = ' width ') {  
            $this. Width ($this. width ());  
          }  

          if (!type | | type = = ' height ') {  
            $this. Height ($this. Height ());}  

        )  
    ;};}) (JQuery);  
$ (' div '). Lockdimensions (' width '). css (' Color ', ' red ');  

Because the plug-in returns this, it is guaranteed to be chained so that it can continue to be modified using the JQuery method, such as CSS (). If your plugin is not returning a simple value, you should usually return this. And, as you might expect, the parameters you pass in can also be accessed in your plugin. So in this example, you can access the type.
5, default values and options

For some complex, customizable plugins, it's a good idea to provide a set of defaults that extend the default values when called. This way, instead of passing in a bunch of arguments when calling a function, you pass in a parameter that needs to be replaced. You can do this:

(function ($) {  

      $.fn.tooltip = function (options) {    

        var settings = {  
          ' location '         : ' Top ',  
          ' background -color ': ' Blue '  
        };  

        Return This.each (function () {          
          ///If there is an option, merge if  
          (options) {   
            $.extend (settings, options);  
          }  

          Other code  

        });}  
    ) (JQuery);  

Key Content

In this example, when the plugin is called, the default location will be replaced with the city ' left ', while Background-color is still ' blue '. This guarantees a high degree of flexibility without requiring the developer to define all possible options.
6, Name space

The right namespace is important for plug-in development, which ensures that your plug-ins are not rewritten by other plugins, and that other code on the page can be avoided. Namespaces can make you live longer, because you can record your own methods, events, data, and so on.
A, plug-in method

In any case, do not add multiple methods to the JQUERY.FN in a single plug-in. Such as:

    (function ($) {  

      $.fn.tooltip = function (options) {//such};  
      $.fn.tooltipshow = function () {//Yes   };  
      $.fn.tooltiphide = function () {//Bad  };  
      $.fn.tooltipupdate = function (content) {//classmate.  };  

    

It is not recommended to use this, messing up the $.fn namespace. To correct this, you can put all the methods into one object and then invoke them by different parameters.

 (function ($) {var methods = {Init:function (options) {//this}, Show:function () {//is}, Hide:function () {//good}, update:function (content)  
      { // !!! }  

      }; $.fn.tooltip = function (method) {//Method calling Logic if (Methods[method]) {Retu  
        RN methods[Method].apply (this, Array.prototype.slice.call (arguments, 1));  
        } else if (typeof method = = = ' object ' | |! method) {return methods.init.apply (this, arguments);  
        } else {$.error (' method ' + method + ' does not exist on Jquery.tooltip ');  

    }      

      };  
}) (JQuery); 
$ (' div '). tooltip ({  //calls the Init method  
      foo: ' Bar '  
    });  
    $ (' div '). ToolTip (' hide '); Calls the Hide method  
    $ (' div '). ToolTip (' Update ', ' This is the new ToolTip content! ');//calls the Update method  

jquery's own extensions also use this plug-in structure.
B, Event

The namespace of the bound event is less known. If your plugin binds an event, it's a good idea to get it into a namespace. This way, if you need to unbind later, it will not affect other functions that are bound to this event. You can use the "." To increase the namespace.

 (function ($) {var methods = {Init:function (options) {return This.each (function (  
           {$ (window). bind (' Resize.tooltip ', methods.reposition);  

         }); }, Destroy:function () {return This.each (function () {$ (window). Unbind ('. tooltip  
           '); })}, Reposition:function () {//...}, Show:function () {//...}, HID  
      E:function () {//...}, update:function (content) {//...}  

      }; $.fn.tooltip = function (method) {if (Methods[method]) {return methods[method].apply (this, Ar  
        Ray.prototype.slice.call (arguments, 1));  
        } else if (typeof method = = = ' object ' | |! method) {return methods.init.apply (this, arguments);  
        } else {$.error (' method ' + method + ' does not exist on Jquery.tooltip ');  }      

      };

    }) (JQuery);  
    $ (' #fun '). ToolTip ();  
 Some time later ... $ (' #fun '). ToolTip (' Destroy ');

In this example, the ToolTip is initialized in the Init method, which binds the reposition method to the ToolTip namespace of the Resize event of the Window object. Later, if the developer needs to remove this tooltip, we can unbind the binding. This will not affect other methods that bind to the Resize event of the Window object.
C, data

When developing plug-ins, you will usually have the need to keep state or check if your plugin has been initialized. Using the data method of jquery is a good way to keep variables. However, instead of saving variables separately, we put them in an object so that they can be accessed uniformly under a namespace.

(function ($) {var methods = {Init:function (options) {return This.each (function () {var $this = $ (this), data = $this. Data (' tooltip '), tooltip = $ (' &L  

             T;div/> ', {text: $this. attr (' title ')});  If the plugin hasn ' t been initialized yet if (! data) {/* do more  
                   Setup Stuff here */$ (this). Data (' tooltip ', {target: $this,  

             Tooltip:tooltip});  
         }  
           });  
                 }, Destroy:function () {return This.each (function () {var $this = $ (this),  

             data = $this. Data (' tooltip ');  
             Namespacing FTW $ (window). Unbind ('. ToolTip ');  
             Data.tooltip.remove (); $this. REmovedata (' tooltip '); })}, Reposition:function () {//...}, Show:function () {//...}, HID  
      E:function () {//...}, update:function (content) {//...}  

      }; $.fn.tooltip = function (method) {if (Methods[method]) {return methods[method].apply (this, Ar  
        Ray.prototype.slice.call (arguments, 1));  
        } else if (typeof method = = = ' object ' | |! method) {return methods.init.apply (this, arguments);  
        } else {$.error (' method ' + method + ' does not exist on Jquery.tooltip ');  

    }      

      };   }) (JQuery);

Using the data method can help you keep variables and states between the various methods of the plug-in. The various variables are placed in an object that can be easily accessed or easily removed.
7, summary and best practices

The jquery plugin can be used to make full use of the library, abstracting common functions and "recycling". The following is a brief summary: Use (function ($) {//plugin}) (jQuery); to wrap your plugin do not repeat the package in the initial range of the plugin unless you return the original value, the this pointer is returned to ensure that the chain does not use a string of parameters, but instead uses an object, and set the default value of a plug-in, do not attach multiple functions for Jquery.fn to your function, event, data attachment to a namespace

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.