Jacco
Jacco

Reputation: 23789

Javascript prevent anonymous function?

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?

Upvotes: 5

Views: 873

Answers (5)

SLaks
SLaks

Reputation: 887767

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) );

Upvotes: 10

kennebec
kennebec

Reputation: 104800

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)});

Upvotes: 1

Amy
Amy

Reputation: 1338

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?

Upvotes: 0

Peter Bailey
Peter Bailey

Reputation: 105908

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.

Upvotes: 1

Dapeng
Dapeng

Reputation: 1726

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
  });
});

Upvotes: -2

Related Questions