Skip to content

Instantly share code, notes, and snippets.

@tgvashworth
Last active December 19, 2015 01:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tgvashworth/5875512 to your computer and use it in GitHub Desktop.
Save tgvashworth/5875512 to your computer and use it in GitHub Desktop.
deferCallable
/**
* 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