jquery Plugin Development

Source: Internet
Author: User

Today in Saturday, played a morning lol, while waiting for the time to talk about the development of jquery plug-ins, hope that the great God advice Spur!

In the software development process needs a certain design pattern to guide the development, with the model, we can better organize our code, and from the previous experience to learn better practice.
According to the description in jquery advanced programming, there are three important ways to develop jquery plugins:

    1. Extend jquery with $.extend ()
    2. Add a new method to jquery through $.fn
    3. Created by using the $.widget () Widget factory method of the jquery UI (this method is rarely used for a while, and it is estimated that you rarely see it!). Oh...... )

Usually we use the second method for simple plug-in development, saying that simplicity is relative to the third way. The third way is to develop more advanced jquery parts, the model developed by the parts with a lot of jquery built-in features, such as plug-in state information automatically saved, a variety of plug-in methods, etc., are very meticulous.
The first approach is too simple, just in the jquery namespace or in the sense of adding a static method to jquery itself. So when we call the method added by $.extend (), we call $.myfunction () directly through the $ symbol without having to check the DOM element $ (). MyFunction ().

Way One, $.extend ()
Defines the plug-in    $.extend ({      gotop:function () {        $ (' html,body '). Animate ({scrolltop:0}, +);}    ); /Call  $ ('. Gotop '). Click (function () {    $.gotop ();  });

The above code adds a Gotop method to jquery through the $.extend () method, which is then called directly through $. This completes a simple jquery plugin.
As you can see, it is convenient to define some of the helper classes in this way, once defined, by using jquery to invoke it wherever needed in the program.

Way Two, $.fn

The first approach is not to use jquery's powerful selectors, to handle DOM elements and to apply the plug-in to the selected element, or to use the second method. Most of the plugins I've seen and used are also created by $.fn, at least for now.

Example syntax for the second way:

$.fn.mypluginname = function () {  //code content}

Add a method to $.fn, name is the name of our plugin, then our plugin code is expanded in this method.
For example, if we change the background color of an element in a page to red, we write:

Define plug-in $.FN.PLUGINBG = function () {        this.css (' backgroundcolor ', ' red ');//Here, this refers to the element selected with jquery, that is: this = $ (element This usage again does not introduce too much    }//call $ (elment). PLUGINBG ();
Pass-the-reference plug

a strong plug-in can be customized to the user, which requires us to develop the plug-in is considered more comprehensive, as far as possible to provide the appropriate parameters.    the extend method of jquery is often used to handle the reception of plug-in parameters, as mentioned above, but it is a case of passing a single object to the Extend method, which is merged into jquery. So we can invoke the methods contained in the new merge object on jquery. When passing multiple objects to the Extend method, it merges all parameter objects into the first one. Also, if an attribute with the same name exists in the object, then the merge will overwrite the previous.  With this, we can define an object in the plug-in that holds the default value of the plug-in parameter, merges the received parameter object onto the default object, and finally implements the user-specified value that is worth the parameter, using the plug-in's default value when the parameter is not specified.

Let's give an example to allow the user to call the plugin when the color is set, the code is as follows:

Definition Plugin $.fn.pluginstyle = function (opt) {var defaults = {' Color ': ' Red ',};    var settings = $.extend (defaults,opt); Return this.css ({' Color ': Settings.color,})}//does not pass the parameter call, the color is set to the default value of Red                $ (Elm). Pluginstyle ();//Parameter call, Color set to Blu e$ (Elm). Pluginstyle ({' Color ': ' Blue '});

In this, the plug-in can receive and process parameters, you can write out more flexible plug-ins.

Object-oriented plugins

  Ask:

To write a complex plug-in, the amount of code is very large, how to organize the code becomes a need to face the problem, there is no good way to organize the code, the overall feeling will be disorganized, but also difficult to maintain, how to do?

  For:

We wrap all the properties of the plugin on an object and use object-oriented thinking to develop it, so everything will be solved!

We will beautify the example above, the code is as follows:

Defines how the Nick object is constructed  var nick = function (Ele, opt) {this    . $element = ele,      this.defaults = {        ' color ': ' Red '      },      this.options = $.extend (this.defaults,opt);  }  Method for defining an object  Nick.prototype = {    handsome:function () {      return this. $element. css ({        ' color ': This.options.color      });    }  }  Using objects in plugins  $.fn.myplugin = function (options) {    //Create entity    var me = new Nick (this, options);    Call its method    return Me.handsome ();  }  Without a parameter call, the color is set to the default value of Red  $ (Elm). Pluginstyle ();  When the parameter is called, the color is set to Blue  $ (Elm). Pluginstyle ({' Color ': ' Blue '});

I feel perfect when I write here, but when I'm ready to publish after dinner, I look at it--oops! It seems there is room for improvement!

The usefulness of an anonymous function

Not only is the development of jquery plug-ins, we should be careful to write any JS code should not pollute the global namespace, because with the increase in the amount of code, if intentionally or unintentionally in the global scope to define some variables, it is difficult to maintain, and other people write code conflicts.
A good practice is to always use the self-invoking anonymous function to wrap your code so that you can use it completely safely and confidently anywhere, with absolutely no conflict issues.
In JavaScript, it is not possible to create scopes conveniently using curly braces, but functions can form a scope in which the code within the domain cannot be accessed by the outside world, and if we put our own code into a function, it does not pollute the global namespace and does not conflict with other code. So we're wrapping all the code with self-invoking anonymous functions.
Finally, the above plug-in code with an anonymous function wrapped up, done!

At the end, or that sentence-hope that the great God's advice to spur me!

jquery Plugin Development

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.