In javascript, method chain calls are very popular, and jQuery users must have a deep understanding of this. In the javascript design pattern, this method is described in detail to implement chained call of methods, you only need to let the methods defined in the prototype return the reference of the Instance Object that calls these methods. Read the code in this book:
(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 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'); }); 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 _$(arguments); };})();
It can be seen that each method ends with "return this", which will pass the object of the method called to the next method on the chain. However, if the data we want to operate on is obtained through asynchronous requests, how can we keep the chained call of methods? Dustin Diaz provides us with a method to ensure the chained call of methods. He is also one of the authors of javascript design patterns.
He first constructed a Queue object, namely:
function Queue() { // store your callbacks this._methods = []; // keep a reference to your response this._response = null; // all queues start off unflushed this._flushed = false;}Queue.prototype = { // adds callbacks to your queue add: function(fn) { // if the queue had been flushed, return immediately if (this._flushed) { fn(this._response); // otherwise push it on the queue } else { this._methods.push(fn); } }, flush: function(resp) { // note: flush only ever happens once 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]) { this._methods.shift()(resp); } }};
- 2 pages in total:
- Previous Page
- 1
- 2
- Next Page