Last active
December 19, 2015 01:19
-
-
Save tgvashworth/5875512 to your computer and use it in GitHub Desktop.
deferCallable
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 callable. Kinda tricky to explain. Basically: | |
* "Don't make newFn callable until I tell you via this trigger callback." | |
* | |
* Example: | |
// Only start logging after 3 seconds | |
var log = function (str) { console.log(str); }; | |
var deferredLog = deferCallable(log, function (done) { | |
setTimeout(done, 3000); | |
}); | |
setInterval(function () { | |
deferredLog(Date.now(), 500); | |
}); | |
*/ | |
var deferCallable = function (newFn, trigger) { | |
var args, | |
pointerFn = function () { | |
// Initially, the pointer basically does nothing, waiting for the | |
// trigger to fire, but we save the arguments that wrapper was called | |
// with so that they can be passed to the newFn when it's ready. | |
args = [].slice.call(arguments); | |
}; | |
// Immediately call the trigger so that the user can inform us of when | |
// the newFn is callable. | |
// When it is, swap round the pointers and, if the wrapper was aleady called, | |
// immediately call the pointerFn. | |
trigger(function () { | |
pointerFn = newFn; | |
if (args) { | |
pointerFn.apply(null, args); | |
} | |
}); | |
// Wrapper the pointer function. This means we can swap pointerFn around | |
// without breaking external references. | |
return function wrapper() { | |
return pointerFn.apply(null, [].slice.call(arguments)); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment