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?
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?
Share Improve this question edited Feb 10, 2010 at 16:47 Jacco asked Feb 10, 2010 at 16:11 JaccoJacco 23.8k18 gold badges91 silver badges106 bronze badges 1-
Your syntax is wrong; you meant
function(){ foo(abc); })
– SLaks Commented Feb 10, 2010 at 16:33
5 Answers
Reset to default 10You 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.
You can hide the word function if you prefer 'curry', but your original method does the same thing without the overhead.
You do not need the argument in the parentheses in the anonymous function- it is still in scope when you define it-
abc = 'some value';
attachEventHandler(elementId, 'click', function( abc ){foo( abc );})
could be:
attachEventHandler(elementId, 'click', function(){foo(abc)});
So in your code you have a function foo() that takes an event as the argument? If that's all you want to do then your attachEventHandler() can be written just as:
attachEventHandler(elementId, 'click', foo);
What's going on there is that instead of calling foo() it's passing a reference to foo().
Is this closer to what you're thinking?
you may even want to take look at some js libs
for example YUI
what you do
YUI().use('node',function(Y){
Y.one("#elementID").on('click', function(){
// do your stuff here
});
});