I quite often have to bind? some function that requires arguments. The solution I use is wrapping the function to bind inside an anonymous function.
function foo( arg_0 ) {
// do stuff with: arg_0
}
function bar() {
var abc;
// stuff happens
abc = 'some value';
attachEventHandler(elementId, 'click', function(){foo( abc );});
}
bar();
Is there a more elegant way of doing this?
You can make a curryer, like this:
function curry(func) {
var functionArgs = Array.prototype.slice.call(arguments, 1);
return function() { return func.apply(this, functionArgs); };
}
Usage:
attachEventHandler(elementId, 'click', curry(foo, abc) );
Alternatively:
Function.prototype.curry = function() {
var func = this, functionArgs = arguments;
return function() { return func.apply(this, functionArgs); };
}
Usage:
attachEventHandler(elementId, 'click', foo.curry(abc) );
That's fine. What you have is essentially the use of a callback or "delegate".
SLaks' curryer is some nice syntactic sugar if you have to do this often within a script.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With