JavaScript Asynchronous Method queue chain implementation code analysis _ javascript skills

Source: Internet
Author: User
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:

The Code is as follows:


(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:

The Code is as follows:


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 callafter 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 );
}
}
};


Then we use it as a tool to build our Asynchronous Method queue chain. With this tool, you can easily build a jQuery plugin that retrieves content from the server and attaches it to the selector.

The Code is as follows:


(Function ($ ){
$. Fn. fetch = function (url ){
Var queue = new Queue;
This. each (function (){
Var el = this;
Queue. add (function (resp ){
Vertex (eldomain.html (resp );
});
});
$. Ajax ({
Url: url,
DataType: 'html ',
Success: function (html ){
Queue. flush (html );
}
});
Return this;
};
}) (JQuery );


In this way, we can obtain the content asynchronously and continue our chain call.

The Code is as follows:


$ ("

")
. Fetch ('/server/navigation.html ')
. AddClass ('column ')
. AppendTo ('# side ');


View the demo page to see the effect.
If there are many items in a queue waiting to respond to the server, what should I do? The author has constructed such a method, which is worthy of reference:

The Code is as follows:


Function fetchTweet (url ){
This. queue = new Queue;
This. tweet = "";
Var self = this;
Ajax (url, function (resp ){
Self. tweet = resp;
Self. queue. flush (this );
});
}
FetchTweet. prototype = {
Linkify: function (){
This. queue. add (function (self ){
Self. tweet = self. tweet. replace (/\ B @ (\ w {1, 20} \ B/g, '$1 ');
});
Return this;
},
FilterBadWords: function (){
This. queue. add (function (self ){
Self. tweet = self. tweet. replace (/\ B (fuck | shit | piss) \ B/g ,"");
});
Return this;
},
AppendTo: function (selector ){
This. queue. add (function (self ){
$ (Self. tweet). appendTo (selector );
});
Return this;
}
};


In this way, we can use the following method to call:

The Code is as follows:


FetchTweet (url). linkify (). filterBadWords (). appendTo ('# status ');


At this point, we already know how to Implement Asynchronous method chain calling, but some questions raised by some comments at the bottom of Asynchronous method queue chaining in JavaScript are worth thinking about. In plug-in $. fn. fetch, only the returned content needs to be appended to the element. Is the Queue necessary? In addition, $. fn. load in jQuery can be fully implemented. If only one callback function is used in Queue, it can be written like this:

The Code is as follows:


(Function ($ ){
$. Fn. fetch = function (url ){
Var queue = new Queue;
This. each (function (){
Var el = this;
$. Ajax ({
Url: url,
Type: 'get ',
DataType: 'json ',
Success: function (resp ){
Optional (el).html (resp ['text1']);
}
});
});
Return this;
};
}) (JQuery );


How do you feel?

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.