Patterns and structure of jquery plugin development

Source: Internet
Author: User
Tags closure extend
patterns and structure of jquery plugin development

jquery Plugin Development

In general, there are two types of jquery plug-ins: A global function that hangs under the jquery namespace, or a static method, or a JQuery object-level approach, a method that hangs under the jquery prototype, This method can also be shared by a JQuery object instance obtained through the selector.

First , in the introduction of the jquery plug-in basic structure and mode, before introducing the next two important methods, and do not know what the reason, the code can not be folded, resulting in a slightly longer overall length, reading, please add patience:

1, $.extend (target, [Object1], [objectn])

This method is primarily used to merge the contents (attributes) of two or more objects into the first object and return the merged first object. If the method has only one parameter target, the parameter expands the jquery namespace, which is hung as a static method under the jquery global object, such as $.ajax in jquery, $.getjson global functions, and so on:

Hang the Hello method under the jquery global object as a static method
$.extend ({ 
    hello:function () {alert ("Hello");} 
});

As another example, expand a homocysteine namespace in the jquery global object:

$.extend ({homocysteine: {}});

and extend the Hello method to the Homocysteine namespace of the previously extended jquery:

$.extend ($.hcy, {
    hello:function () {alert ("Hello");}
});

When you develop a plugin, you can also extend the method to a prototype of jquery, such as:

$.extend ($.fn, {
    hello:function () {alert ("Hello");}
});

It is worth noting that when multiple object parameters are merged, the structure of the first object is destroyed, so an empty object can be passed as the first parameter, such as: $.extend ({}, Object1, object2);

In addition, for deep copies, that is, if the object is also nested, the child object (if there is a property of the same name) is copied and overwritten with all of the properties, you need to set the first parameter deep to true value, such as: $.extend (True, Target, Object1, [objectn]).

2, $.fn.extend (target)

In jquery, $.fn is essentially a prototype of jquery, that is, $.fn = $.prototype, so the method is actually adding a method to the jquery prototype, which is to add the target object's method to the jquery prototype, This way the JQuery object instance can access the added method, which is a common method of jquery plug-in development, especially when adding multiple interfaces. Such as:

Add the Hello, Hello2 method to the jquery prototype
$.fn.extend ({ 
    hello:function () {alert ("hello!");},
    hello2:function () { Alert ("Hello again!";}
});

If you add a single method to a jquery prototype, you can add it using the $.fn.pluginname method, such as:

Add the Hello method to the jquery prototype
$.fn.hello = function () {
    //...            
};

Second, after the development of some jquery plug-ins, slowly explored a set of jquery plug-ins to develop the basic structure and mode. This allows you to focus on the most important logic code in the face of complex and changing needs. In addition, using the same design pattern and architecture makes it easier to fix bugs or develop two of times.

share some of the experiences you encounter and summarize here:

1. Put all the code in the closure (an instant execution function)

At this point, the closure is equivalent to a private scope, external access to internal information, and there is no global variable pollution situation. The official creation development specification is interpreted as: a) avoid global dependencies; b) avoid third-party destruction; c) compatible with the jQuery operator ' $ ' and ' jquery '. As shown below:

(function ($) {
    //local scope use $ to refer to jquery
    //...
}) (JQuery);

This code can be interpreted as the following code:

var JQ = function ($) {
  //code goes here
}; 
JQ (JQuery);

2. Provide default parameter options for plug-ins

A well-scaled plug-in should allow the user to customize parameter options based on requirements and control the behavior of the plug-in, so it is necessary to provide a restore default option. You can set these options by using the Extend method of jquery:

var defaults = {    
    name: "Homocysteine",    
    age:22,
    job: "Student",
    walk:function () {
        //...
    }     
};

$.extend ({}, defaults, Options | | {});

Note: The parameter option can also be set with the following pattern, which is to hang the parameter object under the plug-in namespace:

$.fn.pluginname.defaults = {    
    name: "Homocysteine",    
    age:22,
    job: "Student",
    walk:function () {
        //...
    }     
};

3. Iterate through multiple elements and return

jquery uses the Sizzle selector engine, sizzle can provide you with a multivariate operation for your function (for example, for all class names with the same element). This is one of the best features of jquery, and even if you are not prepared to provide multi-factor support for your plugin during the development of the plugin, preparing for it is still a good practice. In addition, jquery has a very good feature is the method can be cascaded, also known as chained calls, so we should not break this feature, always return an element in the method. Such as:

Function ($) {
    //parameter option setting
    ... Add your plugin code to the jquery prototype, using "Pluginname" as the function name for the plugin.
    $.fn.pluginname = function (options) {
        //traversal of matching elements | | Element collection, and returns this to make a chained call.
        return This.each (function () {
            ///This can be used here to get each individual element (jquery object)
            var $this = $ (this);
 
        });
    };
}) (JQuery);

4. One-time code outside the main loop

This one is important, but it is often overlooked. Simply put, if you have a piece of code that is a bunch of default values, you just need to be instantiated once, instead of having to instantiate every time you call your plug-in function, you should put this code outside the plugin method. This allows your plug-in to run more efficiently and save memory. Such as:

Function ($) {
    ///parameter option set
    var defaults = {    
        name: "Homocysteine",    
        age:22,
        job: "Student",
        walk:function () {
            // ...
        }     
    };
    Add your plugin code to the jquery prototype, using "Pluginname" as the function name for the plugin.
    $.fn.pluginname = function (options) {
        var opts = $.extend ({}, defaults, Options | | {});
    
        Traversing Matching Elements | | Element collection, and returns this to make a chained call.
        return This.each (function () {
            ///This can be used here to get each individual element (jquery object)
            var $this = $ (this);
           // ...
        });
    };
}) (JQuery);

5. Define public methods and private methods

In general, for a jquery plugin, a basic function can work well, but for a more complex plug-in you need to provide a variety of methods and private functions. You might use different namespaces to provide a variety of methods for your plugin, but adding too many namespaces can make your code confusing and robust. So the best solution is to define private functions and methods appropriately. The examples are as follows:

(function ($) {///within our plugin container, define a private method var privatefunction = function () {//code here}; By literally creating an object that stores the common methods we need var methods = {///In the literal object define each individual method Init:function () {//For better
                Flexibility for each individual element that comes from the main function and into each of the selectors in each method executes code return This.each (function () {//Create a jquery object for each individual element
                var $this = $ (this);
        Execute code for example: Privatefunction ()});  }, Destroy:function () {//Executes method return This.each () for each element of the selector (function () {//
        Execute code});
 
    }
    }; $.fn.pluginname = function () {///Get our method, unfortunately, if we use function (method) {} to implement, this will ruin everything var method = arguments[
 
        0];
            Verify if the method exists if (Methods[method]) {//If the method exists, store it for use//NOTE: I'm doing this to make it easier to use each ()
 
        method = Methods[method]; If the method does not exist, verify that the object is an object (JSON object) or that method methods are not passed in} else if (typeof meThod = = = "Object" | |

        !method) {//If we pass in an object parameter, or there is no argument at all, the Init method is called method = Methods.init; } else {//If the method does not exist or the parameter does not pass in, an error is reported.
            The method that needs to be called is not called correctly $.error ("method" + method + "does not exist on Jquery.pluginname");
        return this;
    }//Call our chosen method//again notice how we transfer each () from here to return Method.call (this) on each individual method;
 
}; }) (JQuery);

Notice that I took privatefunction as a global variable inside a function. Given that all code runs within the plug-in container, this practice is acceptable because it is available only in the scope of the plug-in. In the main function (pluginname) in the plug-in, I examined the existence of the method that the incoming parameter points to. If the method does not exist or if the parameter is an object, the Init method is run. Finally, if the passed parameter is not an object but a non-existent method, we will quote an error message.

Here are some examples of usage:

Execute the Init method $ (". ClassName") for each element of the class named ". ClassName"
. Pluginname ();
$ (". ClassName"). Pluginname ("Init");
$ (". ClassName"). Pluginname ("Init", {}); Pass the "{}" object to the Init method as a function parameter
$ (". ClassName"). Pluginname ({});////Pass the "{}" object to the Init method as a function parameter
 
//For each class named ". ClassName" The element executes the Destroy method
$ (". ClassName"). Pluginname ("destroy");
$ (". ClassName"). Pluginname ("Destroy", {}); Pass the "{}" object to the Destroy method as a function parameter//
 
all code can run normally
$ (". ClassName"). Pluginname ("Init", "argument1", "argument2"); Pass "argument1" and "Argument2" to "init"
 
//incorrect use of
$ (". ClassName"). Pluginname ("Nonexistantmethod");
$ (". ClassName"). Pluginname ("Nonexistantmethod", {});
$ (". ClassName"). Pluginname ("argument1"); Attempts to invoke the "Argument1" Method
$ (". ClassName"). Pluginname ("Argument1", "argument2");//will attempt to invoke "Argument1", "Argument2" method
$ (". ClassName"). Pluginname ("privatefunction");//"privatefunction" is not a method

Note: This example code refers to an article on Bole online.

6. Add Persistent Data

In the plug-in development process, sometimes need to save the settings and information in the plug-in, jquery in the $.data function can be useful. When used, it tries to get the data associated with the element, and if the data does not exist, it creates the corresponding data and adds it to the element. Once you've used $.data to add information to an element, make sure you've memorized the remember, and use the $.removedata function to delete the data when you no longer need it. The following example is also an excerpt from the Bole Online article ( in-depth understanding of jquery Plugin Development ):

(function ($) {var privatefunction = function () {//Execute code} var methods = {Init:function (o
 
                ptions) {//Executes the method on each element return This.each (function () {var $this = $ (this);
 
                Try to get settings, if not present, return "undefined" var settings = $this. Data ("Pluginname");
 
                    If the Get settings fails, it is created according to options and default if (typeof settings = = = "undefined") {
                    var defaults = {propertyname: "Value", Onsomeevent:function () {}
 
                    };
 
                    Settings = $.extend ({}, defaults, options);
                Save our newly created settings $this. Data ("Pluginname", settings); } else {/If we get settings, then merge it with options (this is not required, you can choose not to do so) settings = $.extend ({
 
                    }, settings, options); If you want to save the options every time, you can add the following code://$this. Data ("Pluginname", settings);
        }//execute code});
                }, Destroy:function (options) {//Executes code return $ (this) in each element. Each function () {
 
                var $this = $ (this);
            Executes the code//delete element corresponding to the data $this. Removedata ("Pluginname");
        }); }, Val:function (options) {//the code here passes. EQ (0) to get the first element in the selector, we or get its HTML content as our return value Var Somev
 
            Alue = This.eq (0). html ();
        Returns the value return somevalue;
 
    }
    };
 
        $.fn.pluginname = function () {var method = Arguments[0];
            if (Methods[method]) {method = Methods[method];
        arguments = Array.prototype.slice.call (arguments, 1);
        } else if (typeof method = = = "Object" | |!method) {method = Methods.init; } else {$.error ("method" + method + "does not exisT on Jquery.pluginname ");
        return this;
 
    } return Method.apply (this, arguments); }}) (JQuery);

In the preceding code, first verify that the data for the element exists. If the data does not exist, "options" and "Default" are merged, constructed into a new settings, and then saved in the element with $.data ().

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.