JavaScript design pattern 6th chain Call

Source: Internet
Author: User

Chaining calls is a syntax trick.
Function: Enables you to use a small amount of code to express complex operations by reusing an initialization operation.

This technique consists of two parts:
1. A factory that creates objects that represent HTML elements. And a batch of methods to perform certain operations on this HTML element.
Through example comparison: Before and after the code, the concept of chain calls to the preliminary understanding.
Before:

Addevent ($ (' example '), "click", Function () {SetStyle (this, "color", ' green ');  Show (this); })

To perform a chained call:

$ (". Example"). Addevent ("click", Function () {$ (this). SetStyle (' Color ', ' green '). Show (); })

6.1 Structure of the call chain

  function $ () {   var  elements = [];   for (var i=0;len = arguments.length,i<lengt;+ +i) {    var element = arguments[i];    if (typeof  element === "string") {     element = document.getelementbyid (element);     }    if (arguments,length===1) {     return  element;    }    element.push (Element);   }     return elements;  } 

  
 ---------Retrofit--------------------
   step:
   1. Transform this function into a constructor and save those elements as arrays in an instance property.
   2. To have all methods defined in the object referenced by the prototype property of the constructor function return a reference to the instance that invokes the method, then he has the ability to chain-call. The
   3. Home page needs to change the $ function to a factory method. He is responsible for creating objects that support chained calls.
   4. This function should be able to accept parameters in the form of an array of elements so that we can use the same public interface as the original

    (function () {     function _$ (ELS) {     this.elements =[];     for ( Var i=0,len  = els.length;i<len;++i) {      var  Element = els[i];      if (typeof element ===  "string") {        element = document.getelementbyid (Element);       }      this.elements.push (Element);      }    }    window.$ = function () {      return new _$ (arguments);     }   }) () 

 ---------------in-depth transformation-friction friction like the devil's pace, one step, two steps------------------
 
  All objects inherit the method of their prototype object's properties. We can let the several methods defined in the prototype object return a reference to the instance object used to invoke the method. These methods can be chained to the call.
  Example: Add a method to the prototype object that _$ this private constructor. To implement chained calls:

   (function () {   function _$ (ELS) {   }   _$. Prototype = {    each:function (FN) {     for (var i= 0,length = this.elements.length;i<len;++i) {      fn.call (this, This.elements[i]);     }     return this;     },    setstyle:function (prop,val) {     this.each ( Function (EL) {      el.style[prop] = val;      });      return this;    },    show: function () {     var that = this;      This.each (function (EL) {      that.setstyle ("display", "block");      }) &NBSP;&NBSP;&NBSP;&NBSP;&NBsp;return this;    },    addevent:function (TYPE,FN) {      var add = function (EL) {      if ( Window.addeventlistener) {       el.addeventlistener (type,fn,false);       }else if (window.attachevent) {        El.attachevent ("on" +TYPE,FN);      };       This.each (function (EL) {       add (EL);       } );      return this;     }     };    window.$ = function () {     return new _ $ (argments);     }   }  }) ()


-------------------Analysis----------Rubbing on the smooth ground----------
1. The last line of each method of the class is ended with a return this
2. This will pass the object that invokes the method to the next method on the calling connection.

---------test Case------------------mom Wait a long time, although there are many I do not understand, but still want to try, the inner silence of excitement-------

$ (window). addevent (' Load ', function () {$ ("test-1", "Test-2"). Show (). SetStyle (' Color ', ' red '). Addevent ("click",  Function (e) {$ (this). SetStyle (' Color ', ' green '); }) })

-----------Fuck ~o^o~ This way is true when using jquery--------a touch of sadness--and study well ~o~

--------------------------------new chapters continue, Minute fly butterfly (6.2 Design a JavaScript library that supports method invocation)-------------------------------------------------------------There was a feeling that the wood had a scare of urine, Nervous-----------------------
The features of most common JavaScript libraries
1. Events, adding and removing event listeners, normalizing event objects
2.dom: class name management; style Management
3.ajax: Standardize hair processing for XMLHttpRequest

The


 6.3 uses callbacks to get data-------------from a method that supports chained calls (it feels very useful)
   A chapter always describes the usage and usage scenarios:
     See below: zzzzzz
    1. Chained calls are well suited to evaluator methods, but for a value method, we want to return data that is not this.
    2. All the offences that require modification: Use callback techniques to return the data you want. (Fuck, really good ah, dense admire ah, *@_@*)
    3. Hide the total method by example
      The Api1 class uses a normal accessor (which interrupts the call chain), and

Window.api = Window.api | |      function () {var name = "Hello word";       This.setname = function (newname) {name = NewName;      return this;      } this.getname = function () {return name;     }} var o = new API;      Console.log (O.getname ()); Console.log (O.setname ("Meow"). GetName ());

Advanced Mode------> Callback method

window.api1= Window.api2 | |       function () {var name = "Hello word" this.setname = function (newname) {name = NewName;      Retrun this;       }//Important Step This.getname = function (callback) {Callback.call (this,name);      return this; }     }


-------------------------------End 23:40---a little tired-----(-_-) ZZZ slept ~ ~ ~-------------------------


JavaScript design pattern 6th chain Call

Related Article

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.