Created
August 3, 2012 03:49
-
-
Save shiawuen/3244178 to your computer and use it in GitHub Desktop.
simple hacky deffered implementation
This file contains hidden or 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
/** | |
* Simple Hacky Deffered Implementation | |
* | |
* @author Tan Shiaw Uen | |
* @url https://gist.github.com/3244178 | |
* @License MIT | |
**/ | |
(function (win, undef) { | |
/** | |
* cache for local use | |
**/ | |
var slice = Array.prototype.slice; | |
// Constructor | |
var Deffered = win.Deffered = function () { | |
if ( ! (this instanceof Deffered) ) { | |
return new Deffered(); | |
} | |
this._succeed = undef; | |
this._result = []; | |
this._successCbs = []; | |
this._failedCbs = []; | |
}; | |
var processEvent = function(callback, cbList, succeed, result) { | |
cbList.push( callback ); | |
if (this._succeed === succeed) { | |
callback.apply(null, result); | |
} | |
}; | |
var processResults = function (opts) { | |
var cbs = opts.callbacks; | |
var l = cbs.length; | |
this._result = opts.results; | |
this._succeed = opts.succeed; | |
for (;l--;) { | |
cbs[ l ].apply(null, this._result); | |
} | |
}; | |
Deffered.prototype.success = function (callback) { | |
processEvent.call(this, callback, this._successCbs, true, this._result); | |
return this; | |
} | |
Deffered.prototype.fail = function (callback) { | |
processEvent.call(this, callback, this._failedCbs, false, this._failedResult); | |
return this; | |
} | |
Deffered.prototype.resolved = function (/*results params*/) { | |
processResults.call( this, { | |
results: slice.call( arguments ), | |
succeed: true, | |
callbacks: this._successCbs | |
}); | |
} | |
Deffered.prototype.failed = function (/*results params*/) { | |
processResults.call( this, { | |
results: slice.call( arguments ), | |
succeed: false, | |
callbacks: this._failedCbs | |
}); | |
} | |
})(this); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment