首页 > 代码库 > Deffered.js的实现原理

Deffered.js的实现原理

 1 function Deferred () { 2   return this.init(); 3 }
//设置默认的成功函数与失败函数
4 Deferred.ok = function(x) {return x} 5 Deferred.ng = function(x) {throw x} 6 Deferred.isDeferred = function (obj) {
    //判断是否是Deferred的实例
7   return !!(obj && obj._id === Deferred.prototype._id); 8 };
//next 的静态方法
9 Deferred.next = function(fn){10 var d = new Deferred();11 var img = new Image();12 var handler = function(){13 d.canceller();14 d.calls();15 }16 //利用img加载错误触发一个异步处理,常用的还有setTimeout等17 img.addEventListener(‘error‘,handler,false);18 d.canceller = function(){19 img.removeEventListener(‘error‘,handler,false);20 }21 img.src = "data:image/png," + Math.random();22 if(fn) d.callback.ok = fn;23 return d;24 }25 Deferred.wait = function (n) {26 var d = new Deferred(), t = new Date();27 var id = setTimeout(function () {28 d.calls((new Date()).getTime() - t.getTime());29 }, n * 1000);30 d.canceller = function () { clearTimeout(id) };31 return d;32 };33 34 35 Deferred.prototype = {36 _id : 8888, //用来判断实例的时候会有用到37 init : function(){38 this._next = null;39 this.callback = {40 ok : Deferred.ok,41 ng : Deferred.ng42 }43 return this;44 },45 next : function (fun) { return this._post("ok", fun) },46 47 calls : function (val) { return this._fire("ok", val) },48 49 _post : function (okng, fun) {50 this._next = new Deferred();51 this._next.callback[okng] = fun;52 return this._next;53 },54 55 _fire : function (okng, value) {56 var next = "ok";57 58 value = http://www.mamicode.com/this.callback[okng](value);59 60 if (Deferred.isDeferred(value)) {61 value._next = this._next;62 } else {63 if (this._next) this._next._fire(next, value);64 }65 return this;66 }67 }