There seems to be such a famous saying: "Every elegant interface is backed by the implementation of ". The most obvious example is jQuery. The reason for this complexity is that it is complicated. Although some implementations are relatively concise, they cannot be compatible. Of course, there are always exceptions in the world, such as mootools, but the interface exposed to our eyes does not know whether it is the parent class. The structure is clear but not clear. The reason why I say this is because asynchronous queuing is really complicated, but I will try to make the API simple and easy to use. There is no new instantiation, there is no distinction between instances and class methods, chain, and other fashionable things are used. The source code is provided below:
; (Function (){
Var dom = this. dom = this. dom | {
Mix: function (target, source, override ){
Var I, ride = (override = void 0) | override;
For (I in source ){
If (ride |! (I in target )){
Target [I] = source [I];
}
}
Return target;
}
}
//////////////////////////////////////// //////////////////////////////
// ===================================== Asynchronous queuing module ================ ======================================
Var Deferred = dom. Deferred = function (fn ){
Return this instanceof Deferred? This. init (fn): new Deferred (fn)
}
Var A_slice = Array. prototype. slice;
Dom. mix (Deferred ,{
Get: function (obj) {// make sure this is a Deferred instance
Return obj instanceof Deferred? Obj: new Deferred
},
OK: function (r) {// Transmitter
Return r
},
Ng: function (e) {// Transmitter
Throw e
}
});
Deferred. prototype = {
Init: function (fn) {// initialization, create two queues
This. _ firing = [];
This. _ fired = [];
If (typeof fn = "function ")
Return this. then (fn)
Return this;
},
_ Add: function (okng, fn ){
Var obj = {
OK: Deferred. OK,
Ng: Deferred. ng,
Arr: []
}
If (typeof fn = "function ")
Obj [okng] = fn;
This. _ firing. push (obj );
Return this;
},
Then: function (fn) {// _ add method 1, used to add forward callback
Return Deferred. get (this). _ add ("OK", fn)
},
Once: function (fn) {// _ add method 2, used to add negative callback
Return Deferred. get (this). _ add ("ng", fn)
},
Wait: function (timeout ){
Var self = Deferred. get (this );
Self. _ firing. push (~~ Timeout)
Return self
},
_ Fire: function (okng, args, result ){
Var type = "OK ",
Obj = this. _ firing. shift ();
If (obj ){
This. _ fired. push (obj); // pushes the executed callback function package from one queue to another.
Var self = this;
If (typeof obj = "number") {// if the operation is delayed
Var timeoutID = setTimeout (function (){
Self. _ fire (okng, self. before (args, result ))
}, Obj)
This. onabort = function (){
ClearTimeout (timeoutID );
}
} Else if (obj. arr. length) {// for parallel operations
Var I = 0, d;