jquery Plugin Authoring and chained programming model

Source: Internet
Author: User

jquery plugin writing and chain programming model summary

jquery has greatly improved our efficiency in writing JavaScript, allowing us to happily write code and make a variety of special effects. In most cases, we are using jquery plugins developed by others, and today we'll look at how to make jquery plugins for our common functions and then manipulate the DOM like jquery.

First, jquery plug-in development quickly get started

1. jquery Plugin Template

With regard to the writing of jquery plugins, we can write jquery plugins by adding a new function to Jquery.fn. The name of the property is the name of your plugin, and its template is as follows:

(function ($) {   $.fn.myjqplugin = function () {      //todo:add your code   }}) (JQuery);

Where Myjqplugin is the name of your plugin, function code is your plug-in implementation code.

2. Interacting with the DOM

After giving the plugin a good name, you can write our code below, but before you write it, you 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.myjqplugin = function () {        //No need to use $ (this)        //$ (this) is the         same as $ ($ (' #element ')) This.html ("Hello,world");      This.click (function () {         this.hide ();//Note that this is no longer pointing to the jquery element, where this is a pointer to the current function object      });     

Here we have to refer to this point problem, for example, we want to implement a function, click on the DOM element, hide the current element, although this point to the JQuery object, but in click, the point of this has changed, Point to the function it is in. So we access the current element in the click Method, we will pass the variable, the implementation method is as follows:

(function ($) {  $.fn.myjqplugin = function () {        //No need to use $ (this)        //$ (this) is the         same as $ ($ (' #element ')) This.html ("Hello,world");      var $this = $ (this);       This.click (function () {         $this. Hide ();//Note that this is no longer pointing to the jquery element, this is the current function object      });}   ;  }) (JQuery);  

We declare the $this variable to hold the This object so that when we need to use the current element, we can use the $this directly. Let's test it with a complete example:

The code for the HTML page is as follows:

<! DOCTYPE html>

The JS code for the jquery plugin is as follows:

(function ($) {   $.fn.myjqplugin = function () {      this.css ("Color", "red");//Font color is red      this.hide ();        This.slidedown ($);   Hide it and then show it through Slidedown      var $this = $ (this);      This.click (function () {      $this. html ("Thanks,good bye!");//display information, then fade out      $this. FadeOut ()      ;})   (JQuery);

The function of this plugin is to first let the element drop-down display, and then click on the element to display good-bye message, and then after 2s fade out. Here you can try to use this in the Click event.

Second, the chain operation of jquery

1. Why should I use chain-type operation?

In fact, a chained operation simply adds the return this to the method on the object. Return the object back, of course, the object can continue to invoke the method, so you can chain-operated. So, simply implement one:

Define a JS class function Demo () {}//to extend its prototypedemo.prototype ={    setname:function (name) {        this.name = name;        return this;    },    getname:function () {        return this.name;    },    setage:function (age) {        this.age = Age;        return this;    }}; Factory functions Function D () {    return new Demo ();} To implement a chained call to D (). SetName ("CJ"). Setage (+). SetName ();

A general explanation:

Save code and the code looks more elegant. For example, if you don't have a chain, you might want to write code like this:

This code calls two times document.getElementById to get the elements of the DOM tree, which consumes a large number, and writes two lines, and the chain simply writes a line, saving the code ...

But we can also use the cache element ah. Like what:

And the two lines are not much more code than the line, and even the corresponding package makes the code more.
The worst thing is that all of the object's methods return the object itself, meaning there is no return value, which is not necessarily appropriate in any environment.

2, then why should we use chain-like operation?

For a better asynchronous experience, JavaScript is a non-blocking language, so instead of blocking, he can't block, so he needs to drive through events, asynchronously, to do something that needs to block the process.

But asynchronous programming is a crazy thing ... It doesn't matter when the runtime is detached, but it's also separate when writing code ...

What are the common asynchronous programming models?

(1) callback function :

The so-called callback function, which means to register a function somewhere in the system, let the system know the existence of the function, and then, later, when an event occurs, call the function to respond to the event.

function Fun (num, callback) {    if (num < 0) {       alert ("Score cannot be negative, input error!");    } else if (num = = 0) {       alert ("The student may not have taken the exam!") ");    } else {       alert ("Call high-level function handling!");       SetTimeout (function () {callback ();}, 1000);    

Here callback is the callback function. You can see that callback is called only if NUM is a non-negative number.
But the problem, if we do not look inside the function, we do not know when the callback will be called, under what circumstances to invoke, there is a certain coupling between the code, the process will also produce some confusion.

Although a callback function is a simple and easy-to-deploy way to implement async, it is not good enough from the programming experience.

(2) chain-Asynchronous :

I think the most commendable thing about chained operation is that it solves the problem that the execution flow of asynchronous programming model is not clear. jquery in $ (document). Ready is a great illustration of this idea. Domcontentloaded is an event that most of jquery's operations do not work until the DOM is loaded, but jquery's designers do not treat him as an event, but instead turn to a "select object, manipulate it" mentality. $ selects the Document object, and ready is the way it operates. The process problem is very clear, and the way to the back of the chain is to be executed.

(function () {var isready=false;//To determine if the Ondomready method has been executed by Var readylist= [];//The method to be executed first temporarily exists in this array var timer;//timer handle       Ready=function (FN) {if (IsReady) Fn.call (document);       else Readylist.push (function () {return fn.call (this);});    return this;       } var ondomready=function () {for (Var i=0;i<readylist.length;i++) {readylist[i].apply (document);    } readylist = null;          } var bindready = function (evt) {if (isReady) return;          Isready=true;          Ondomready.call (window);       if (Document.removeeventlistener) {Document.removeeventlistener ("domcontentloaded", Bindready, false);          } else if (document.attachevent) {document.detachevent ("onreadystatechange", Bindready);             if (window = = window.top) {clearinterval (timer);          timer = null;    }       }    }; if (Document.addeventlistener) {Document.addeventlistener ("domcontentloaded", Bindready, false); }else if (document.attachevent) {document.attachevent ("onreadystatechange", function () {if (/loaded|compl          ete/). Test (Document.readystate)) Bindready ();          }); if (window = = window.top) {timer = setinterval (function () {try{isready| |                Document.documentElement.doScroll (' left ');//can execute doscroll under IE to determine if the DOM is loaded} catch (e) {             Return          } bindready ();       },5);  }    } })();

The above code cannot be used with $ (document). Ready, and should be window.ready.

(3) Promise :

The asynchronous programming model in Commonjs also continues the idea that each asynchronous task returns a Promise object that has a then method that allows the callback function to be specified.

So we can write this:
F1 (). Then (F2). then (F3);
We don't need to focus too much on implementation, we don't have to understand asynchrony, we can do asynchronous programming by simply selecting the object through the function and then doing it.

third, the characteristics of the maintenance chain-type development

In jquery, a plug-in tightly modifies the collected elements, and then returns this element for 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. The following code:

(function ($) {    $.fn.resize = function (type, value) {       return This.each (function () {        var $this = $ (this); 
   
    if (!type | | type = = ' width ') {           $this. Width (value);        }        if (!type | | type = = ' height ') {           $this. Height (value);}}     );    };  
   

The calling method is as follows:

iv. Summary of jquery plugin writing

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 plug-in
    • Unless you return the original value, the this pointer is returned to guarantee a chain-
    • Instead of using a string of parameters, use an object and set the default value
    • A plugin, do not attach multiple functions for Jquery.fn
    • For your functions, events, data attachment to a namespace

v. References

jquery Plugin Development http://www.cnblogs.com/playerlife/archive/2012/05/11/2495269.html

How jquery chained operations are implemented and why chained operations are http://www.jb51.net/article/33342.htm-

jquery Plugin Authoring and chained programming model

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.