In JavaScript, chained calls to methods are popular, and friends using jquery must have a deep understanding. This method is described in more detail in the JavaScript design pattern, and the chained invocation of the method is only necessary for the method defined in the prototype to return a reference to the instance object that invokes the method, and look at this code in the book:
The following are the referenced contents: (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);
}
};
_$.prototype = {
each:function (FN) {
for (var i = 0, len = this.elements.length i < len; ++i) {
Fn.call (this, this.elements[i]);
}
return to this;
},
setstyle:function (prop, Val) {
This.each (function (EL) {
El.style[prop] = val;
});
return to this;
},
show:function () {
var that = this;
This.each (function (EL) {
that.setstyle (' Display ', ' block ');
});
return to 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 to this;
}
};
window.$ = function () {
return new _$ (arguments);
};
})(); |
As you can see, each method ends with "return this", which passes the object that invokes the method to the next method on the chain. But if the data we want to manipulate is obtained by an asynchronous request, how do we keep a chained call to the method? Dustin Diaz provides us with a way to ensure chained calls to methods, and he is also one of the authors of the JavaScript design patterns book.
He first constructed a queue object, namely:
The following is the referenced content: Function Queue () { //Store your callbacks this._methods = []; //Keep a reference to your respon Se this._response = null; //All queues start off unflushed this._flushed = false; } Queue.prototype = { //Adds callbacks to your Queue add:function (FN) { &nbs P If the queue had been flushed, return immediately if (this._flushed) { &nb sp; fn (this._response); //Otherwise push it on the queue } else { This._methods.push (FN); } }, flush:function (resp) { //Note:flush only ever happens once &nbs p; if (this._flushed) { return; } //Store your response for subsequent calls after flush () this._response = Resp //mark that it ' s been flushed this._flushed = true; Shift ' em out and call ' em back while (This._methods[0]) { t His._methods.shift () (RESP); } } }; |