简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM