码迷,mamicode.com
首页 > Web开发 > 详细

Deffered.js的实现原理

时间:2014-07-05 20:50:56      阅读:291      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   art   cti   

 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.ng 42 } 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 = 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 }

 

Deffered.js的实现原理,布布扣,bubuko.com

Deffered.js的实现原理

标签:style   blog   color   os   art   cti   

原文地址:http://www.cnblogs.com/afrog/p/3826150.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!