Created
December 11, 2012 14:44
-
-
Save bloodyowl/4259043 to your computer and use it in GitHub Desktop.
Simple Defer
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
;(function(){ | |
var slice = [].slice | |
function push(array, value, length, callback){ | |
var currentLength = array.push(value) | |
, self = this | |
if(currentLength === length) self.result = callback.apply(null, array) | |
} | |
function Defer(){ | |
var args = slice.call(arguments) | |
, self = this | |
, i = 0 | |
, length = args.length | |
, item | |
, stack = self.stack = [] | |
if(!(self instanceof Defer)) return Defer.apply(new Defer, arguments) | |
window.setTimeout(function(){ | |
for(;i < length; i++) { | |
item = args[i] | |
push.call(self, stack, typeof item == "function" ? item() : item, length, self.callback) | |
} | |
}, 0) | |
return self | |
} | |
Defer.prototype.then = function(callback){ | |
var self = this | |
self.callback = callback | |
return self | |
} | |
window.Defer = Defer | |
})() | |
new Defer(function(){return "foo"}, | |
function(){return "bar"}, | |
function(){return "baz"}) | |
.then(function(){console.log(arguments); return arguments}) | |
// this.callback : "then" argument | |
// this.result : this.callback() | |
// this.stack : results of "Defer" arguments |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment