Skip to content

Instantly share code, notes, and snippets.

@jdfm
Last active December 25, 2015 21:49
Show Gist options
  • Save jdfm/7045128 to your computer and use it in GitHub Desktop.
Save jdfm/7045128 to your computer and use it in GitHub Desktop.
mutableBind - Keep the wrapper, redefine everything else.
/**
* Mutable Binds.
*
* Why are mutable binds needed?
* I don't know about "needed", I came up with the idea because I was
* curious about if it would work, how it would work, and if there are
* any use cases. As for the use cases, I don't really know. If you can
* find a legitimate use case, let me know, I'd be happy to hear from
* you.
*
* What can change in a mutable bind?
* The wrapped function
* The 'this' context
* The arguments passed from the wrapper to the wrapped function
*
* The redefine method:
* Each mutably bound function comes with a redefine method, this is how
* you can swap out the above mentioned resources. If you pass undefined
* as the new callable item it will simply reuse the old function you
* originally used to create the bind.
*/
var mutableBind = (function(){
var _slice = Array.prototype.slice;
// mutableBind maker
return function(callable, context/*, arg1, arg2, ..., argN*/){
var lambda = function(){},
args;
// ignore non-functions
if(typeof callable !== 'function'){
throw new TypeError('MutableBind must be called on a function.');
}
// arguments that will be passed by default to callable
args = _slice.call(arguments, 2);
// the wrapper that will call the callable
var wrapper = function(){
return callable.apply(context, args.concat(_slice.call(arguments)));
};
// redefine the elements of the wrapper as needed
wrapper.redefine = function(newCallable, newContext/*, newArg1, ..., newArgN*/){
if(!newCallable && typeof newCallable !== 'function'){
throw new TypeError('MutableBind.redefine must be called on a function or a falsey value.');
}
callable = newCallable || callable;
lambda.prototype = callable.prototype;
wrapper.prototype = new lambda();
context = newContext || context;
args = _slice.call(arguments, 2);
};
lambda.prototype = callable.prototype;
wrapper.prototype = new lambda();
return wrapper;
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment