1

Suppose one has a function:

function doSomething(){
    attachEvent("click", function(){
         //there is a lot of code in this anonymous function
         //It may need to be defined somewhere else as a named function             
         doSomethingElse = variable;
    });
}

How would one define it somewhere else and pass in a variable

function doSomething(){
     //this fires straight away 
     attachEvent("click", doNamedFunction(this.variable)); 
}

function doSomething(){
    //works but arguments aren't being passed
    attachEvent("click", doNamedFunction);
}

//I am defined as a named function instead of an anonymous function
function doNamedFunction(arg){
     doSomethingElse = arg;
     //do lots of other stuff below
}

So the question is how to declare named functions and pass arguments in place of anonymous functions, or do you always need to use anonymous functions as callbacks..?

Many Thanks in advance!

1 Answer 1

2

You have to wrap your function in an anonymous function, or else use the .bind() API that's available in newer browsers:

    attachEvent("click", doNamedFunction.bind(undefined, this.variable));

The .bind() call returns a function that'll invoke "doNamedFunction" with undefined as the this value and your given parameter. Except for some (interesting) details, you can think of .bind() as being a mechanism to create the anonymous function for you.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks so much! I think I'll wrap the function in an anonymous function.
Unrelated to event hanlding, but a side note, newer versions of setTimeout allow for the ...rest parameter. setTimeout(function(a, b, c) { console.log(a, b, c); }, 1, 'seven', 'eight', 'nine'); Figured it'd be worth a mention since it's new and doesn't require wrapping or binds, but could be used in similar situations.
@MattKenefick yes that's true, though browser support (esp. across mobile browsers) seems iffy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.