Last active
August 29, 2015 14:02
-
-
Save yangjunjun/53c5b1ba7b1a0b0c07a3 to your computer and use it in GitHub Desktop.
Defer 对象的简单实现
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Defer 对象的简单实现 | |
// 主要实现的Defer 的done、fail、then、always方法 | |
(function(window){ | |
var Defer = function(){ | |
return Defer.prototype.init(); | |
} | |
Defer.prototype.init = function(){ | |
this.state = 'init'; | |
this.queue = { | |
success:[], | |
fail:[], | |
always:[] | |
} | |
return this; | |
} | |
Defer.prototype.resolve = function(){ | |
this.state = 'resolved'; | |
this.fire(); | |
} | |
Defer.prototype.reject = function(){ | |
this.state = 'rejected'; | |
this.fire(); | |
} | |
Defer.prototype.fire = function(){ | |
if(this.state == 'resolved'){ | |
var i = 0; | |
for(;i < this.queue.success.length; i++){ | |
this.queue.success[i](); | |
} | |
} | |
else if(this.state == 'rejected'){ | |
var i = 0; | |
for(;i < this.queue.fail.length; i++) | |
this.queue.fail[i](); | |
} | |
var i = 0; | |
for(; i < this.queue.always.length; i++){ | |
this.queue.always[i](); | |
} | |
} | |
Defer.prototype.promise = function(){ | |
var self = this; | |
return{ | |
done: function(callback){ | |
self.queue.success.push(callback); | |
// 为了能够链式操作 | |
return this; | |
}, | |
fail: function(callback){ | |
self.queue.fail.push(callback); | |
return this; | |
}, | |
then: function(doneCallback, failCallback){ | |
self.queue.success.push(doneCallback); | |
self.queue.fail.push(failCallback); | |
return this; | |
}, | |
always: function(callback){ | |
self.queue.always.push(callback); | |
return this; | |
} | |
} | |
} | |
window.Defer = Defer; | |
})(window) | |
// | |
// test | |
// | |
function test(){ | |
var defer = Defer(); | |
setTimeout(function(){ | |
alert('Success'); | |
defer.resolve(); | |
// defer.reject(); | |
}, 1000); | |
return defer.promise(); | |
} | |
test().done(function(){ | |
alert('done 01'); | |
}).done(function(){ | |
alert('done 02') | |
}).done(function(){ | |
alert('done 03') | |
}).fail(function(){ | |
alert('fail 01') | |
}).fail(function(){ | |
alert('fail 02') | |
}).always(function(){ | |
alert('always 01') | |
}).always(function(){ | |
alert('always 02') | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment