Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 695
Jacco Avatar asked Feb 10 '10 16:02

Jacco


2 Answers

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) );
like image 117
SLaks Avatar answered Nov 07 '22 11:11

SLaks


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.

like image 1
Peter Bailey Avatar answered Nov 07 '22 10:11

Peter Bailey