Write jquery plugin what? You're not writing jquery plugins yet.

Source: Internet
Author: User

Http://www.cnblogs.com/Leo_wl/p/3409083.html

Objective

With web development today, jquery is almost essential, and even the VS artifact has been built into the jquery and UI Web projects in version 2010. As for the use of jquery benefits here is not to repeat, used to know. Today we are going to discuss the jquery plug-in mechanism, jquery has thousands of third-party plug-ins, sometimes we write a separate function, but also want to combine it with jquery, you can use the jquery chain call, which will extend jquery, written in the form of plug-ins, Here is a demo of a simple extended jquery object:

        Sample: The method for extending the JQuery object, Bold () is used to bold the font.        (function ($) {            $.fn.extend ({                "bold": function () {///<summary>///bold                    font                    ///</ Summary>                    return this.css ({fontweight: "bold"});})        (JQuery);

Call Mode:

This is a very simple extension. Next, we will parse the above code in one step.

First, the plug-in mechanism of jquery

To make it easier for users to create plugins, jquery provides the Jquery.extend () and JQuery.fn.extend () methods.

1. The Jquery.extend () method has an overload.

Jquery.extend (object), a parameter used to extend the jquery class itself, that is, to add a new function on the jquery class/namespace, or a static method, such as a jquery built-in Ajax method with Jquery.ajax () This is called a bit like "class name. Method Name" static method invocation. Let's also write an example of Jquery.extend (object):

        Extends the JQuery object itself        jquery.extend ({            "MinValue": function (A, b) {///<summary>///                compares two values, returns the minimum value                ///</summary>                return a < b a:b;            },            "MaxValue": function (A, b) {                ///<summary>
   ///compares two values, returns the maximum value                ///</summary>                return a > B? a:b;            }        );        Call        var i = n; j = 101;        var Min_v = $.minvalue (i, j); Min_v equals        var max_v = $.maxvalue (i, j);//Max_v equals 101

Overloaded version: Jquery.extend ([deep], Target, Object1, [objectn])

   extends an object with one or more other objects, returning the extended object.
   If target is not specified, the jquery namespace itself is extended. This helps plug-in authors add new methods to jquery.  
   If the first argument is set to True, jquery returns a deep copy, recursively copying any objects found. Otherwise, the copy will share the structure with the original object.  
   undefined properties will not be copied, but properties inherited from the object's prototype will be copied.
Parameters
   deep :       are optional. If set to True, the merge is recursive.
   Target :      The object to be modified.
   Object1 :   The object to be merged into the first object.
   objectn :   Optional. An object to be merged into the first object.
Example 1:
Merges settings and options, modifies and returns settings.
var settings = {validate:false, limit:5, Name: "foo"};&NBSP;
var options = {validate:true, name: "Bar" }; 
Jquery.extend (settings, options);
Result:
Settings = = {Validate:true, limit:5, Name: ' Bar '}

Example 2:
Merge defaults and options without modifying the defaults.
var empty = {}; 
var defaults = { validate: false, limit: 5, name: "foo" }; 
var options = { validate: true, name: "bar" }; 
var settings = jQuery.extend(empty, defaults, options);
结果:
settings == { validate: true, limit: 5, name: "bar" } 
empty == { validate: true, limit: 5, name: "bar" }
这个重载的方法,我们一般用来在编写插件时用自定义插件参数去覆盖插件的默认参数。

JQuery.fn.extend (object) extends the set of jQuery elements to provide new methods (often used to make plug-ins).

First, let's see what FN is. If you look at the jquery code, it's not hard to find.

Jquery.fn = Jquery.prototype = {

Init:function (Selector, context) {...};
};

The original Jquery.fn = Jquery.prototype, which is the prototype of the JQuery object. The JQuery.fn.extend () method is the prototype method for extending the jquery object. We know that the method of extending the prototype is equivalent to adding a "member method" to the object, the class's "member method" to the object of the class to be called, so using the JQuery.fn.extend (object) extension method, an instance of the jquery class can use this "member function". The JQuery.fn.extend (object) and Jquery.extend (object) methods must be separated.

Second, self-executing anonymous function/closure

     1. What is a self-executing anonymous function?     
   It is a function like this: (function {//code}) ();
    2. Question Why (function {//code}), can be executed, and function {//code} ();
    3. Analysis      
        (1). First, Be aware of the difference between the two:     (function {//code}) is an expression, and function {//code} is a functional declaration.     
       (2). Second, JS "precompiled" Features:     JS in the "pre-compilation" stage , the function declaration will be interpreted, but it will be token.      
       (3). When JS executes to function () {// Code} (); JS skips function () {//code}, attempting to execute () because function () {//code} has been interpreted in the "precompiled" stage; &NBSP;&NBSP;&NBSP;&NBSP
    When JS executes to (function {//code}) (), because (function {//code}) is an expression, JS will go to solve it to get the return value, because the return value is a function, therefore encountered (), it will be executed.

In addition, the method of converting a function to an expression does not necessarily depend on the grouping operator (), and we can also use the void operator, the ~ operator, and the operator ...

For example:
Plugin notation in the bootstrap framework:
!function ($) {
Do something;
} (JQuery);

And
(function ($) {
Do something;
}) (JQuery); is one thing.

The biggest use of anonymous functions is to create closures (which is one of the features of the JavaScript language), and you can also build namespaces to reduce the use of global variables.
For example:
var a=1;
(function () () {
var a=100;
})();
alert (a); Pop up 1
More closures and anonymous functions can see the anonymous functions of javascript with self-executing this post.

Three or one step by step package jquery Plugin

Next, let's write a highlight Jqury plugin.
1. Set a closure area to prevent the plug-in "pollution"

Closure-qualified namespace (function ($) {    }) (Window.jquery);

2.jquery.fn.extend (object) extends the JQuery method, making plugins

Closure-qualified namespace (function ($) {    $.fn.extend ({        "highLight": function (options) {            //do something}}    );}) (Window.jquery);

3. Give plug-in default parameters, implement plug-in function

Closure-qualified namespace (function ($) {    $.fn.extend ({        "highLight": function (options) {            var opts = $.extend ({}, Defaluts, Options); Use the Jquery.extend override plugin default parameter            This.each (function () {///  This is the jquery object                //Traverse all the DOM to be highlighted when calling HighLight () Plug-in is a collection of time.                var $this = $ (this);//Gets the jquery object for the current DOM, where this is the DOM of the current loop                //Set the DOM style according to the parameters                $this. css ({                    BackgroundColor:opts.background, Color:opts.foreground});})    ;    Default parameter    var defaluts = {        foreground: ' Red ',        background: ' Yellow '    };}) (Window.jquery);

In this step, the basic function of the highlight plugin is already available. The calling code is as follows:

$ (function () {    $ ("P"). HighLight ();//Call Custom Highlight plugin});

This can only be called directly, not chained. We know that Jquey can be chained, that is, you can invoke multiple methods on a jquery object, such as:
$ (' #id '). CSS ({margintop: ' 100px '}). Addattr ("title", "Test");
However, the above plug-in, it can not be so chained to call. For example: $ ("P"). HighLight (). css ({margintop: ' 100px '}); The CSS method will not be found because the jquery object was not returned after the function was completed with my custom plugin. Next, return the jquery object, and let our plug-in also support chaining calls. (In fact, it is very simple, that is, the implementation of our plug-in code when the jquery to return the image, and the above code is no different)

View Code

4. Exposing public methods to others to expand your plugin (if required)
For example, the highlight plugin has a format method to highlight the text, then we can write it as public, exposed to the plug-in users, different use of according to their own needs to rewrite the format method, so that the highlighted text can be rendered in different formats.

    A common format method. The default is bold, and the user can override the method to achieve different formatting effects.    $.fn.highlight.format = function (str) {        return "<strong>" + str + "</strong>";     }

5. Plug-in private methods
Sometimes, our plugins need some private methods that cannot be accessed by the outside world. For example, we need a method inside the plugin to detect whether the parameters passed in when the user invokes the plugin conform to the specification.
6. Other settings, such as: adding support for your plugin to the metadata plugin will make it more powerful.

The full highlight plugin code is as follows:

Closure-qualified namespace (function ($) {$.fn.extend ({"HighLight": function (Options) {///check whether the arguments passed in by the user are legitimate            if (!isvalid (options)) return this; var opts = $.extend ({}, defaluts, options); Overwrite plug-in default parameters with Jquery.extend return This.each (function () {//This is the jquery object.                Return here to support chaining calls//traversing all the DOM to be highlighted when calling the HighLight () plugin is a collection. var $this = $ (this); Gets the current dom of the JQuery object, where this is the DOM of the current loop//set the DOM style according to the parameters $this. css ({backgr                OundColor:opts.background, color:opts.foreground});                Format highlighted text var markup = $this. HTML ();                Markup = $.fn.highlight.format (markup);            $this. HTML (markup);        });    }    });    Default parameter var defaluts = {foreground: ' Red ', background: ' Yellow '}; A common format method.    The default is bold, and the user can override the method to achieve different formatting effects. $.fn.highlight.format = FunctiOn (str) {return "<strong>" + str + "</strong>"; }//Private method, check whether the parameter is legal function isValid (options) {return!options | | (Options && typeof options = = = "Object")?    True:false; }}) (Window.jquery);

Call

        Call        //caller overwrite plugin exposed common method        $.fn.highlight.format = function (txt) {            return "<em>" + txt + "</em>" 
   }        $ (function () {            $ ("P"). HighLight ({foreground: ' Orange ', background: ' #ccc '});//Invoke Custom highlight plugin        });

If you find the content of the text is wrong welcome communication point!

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.