jquery plugin writing and chain programming model summary

Source: Internet
Author: User

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 the

gives the plugin a good name, we can write our code below, but before writing it, we 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  = Span style= "color: #0000ff;" >function   () { //  //  $ (this) with $ ($ (' #elemen      T ')) is the same as  this . HTML ("Hello,world"  this . Click (function   () { this . Hide (); //  Note here This is no longer pointing to the jquery element, where this is pointing to the current function object    });  }; }) (JQuery); 

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 here no longer points to the jquery element, where this is pointing to 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><HTML><Head>    <title></title>    <Scriptsrc= "Jquery.js"type= "Text/javascript"></Script>    <Scriptsrc= "1.js"type= "Text/javascript"></Script></Head><Body><DivID= "Container"style= "width:800px;height:200px; border:2px #000 solid;padding:20px;font-size:20px;">Hello,world</Div></Body><Scripttype= "Text/javascript">  $('#container'). Myjqplugin (); </Script></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 (200);//hide it and show it through Slidedown      var$ This= $( This);  This. Click (function(){      $ This. html ("Thanks,good bye!");//display information, then fade out$ This. FadeOut (2000);   }); }}) (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 classfunctionDemo () {}//extend its prototype.Demo.prototype ={setName:function(name) { This. Name =name; return  This; }, GetName:function () {        return  This. Name; }, Setage:function(age) { This. Age =Age ; return  This; }}; ////Factory functionfunctionD () {return NewDemo ();}//to implement a chained invocationD (). 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:

document.getElementById ("Ele"). DoSomething (); document.getElementById (

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:

var ele = document.getElementById ("Ele"

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 ();}, +);    

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(){    varisready=false;//determine if the Ondomready method has been executed   varreadylist= [];//put the method that needs to be executed first in this array   varTimer//Timer Handleready=function(FN) {if(IsReady) Fn.call (document); ElseReadylist.push (function() {returnFn.call ( This);}); return  This; }    varondomready=function(){        for(vari=0;i<readylist.length;i++) {readylist[i].apply (document); } readylist=NULL; }    varBindready =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|complete/). Test (Document.readystate)) Bindready ();          }); if(Window = =window.top) {Timer= SetInterval (function(){             Try{IsReady|| Document.documentElement.doScroll (' left ');//under IE can execute DoScroll judge whether 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);    }     });  }; }) (JQuery); 

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-

Cloud drizzling

QQ Exchange Group: 243633526

Blog Address: http://www.cnblogs.com/yunfeifei/

Disclaimer: The original text of this blog only represents my work in a certain time to summarize the views or conclusions, and my unit does not have a direct interest in the relationship. Non-commercial, unauthorized, post please keep the status quo, reprint must retain this paragraph statement, and in the article page obvious location to the original connection.

If you feel that my blog is helpful to everyone, please recommend supporting one, give me the motivation to write.

jquery plugin writing and chain programming model summary

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.