the right way to pass variable to a callback function

10,588

Solution 1

Both of your examples are wrong.

Your first example creates a parameter to the callback method named someVar; it will become the event object that jQuery passes to the handler method.

The second example calls the method immediately, then passes its result to the click method as an event handler.

You you need to pass a function expression that calls your function with a parameter from the outer scope (using a closure):

$('#div').click(function() { someFunction(someVar); });

Solution 2

The click callback function will be passed a jQuery Event object, not someVar.

You have to call your function yourself within the callback function.

$('#div').click(function(ev) {
    someFunction(someVar);
}

function someFunction(someVar) {
     ...
}

Alternatively, do:

$('#div').click({someVar: someVar}, someFunction);

function someFunction(ev) {
    // your var is now in ev.data.someVar
}
Share:
10,588
ilyo
Author by

ilyo

Updated on June 19, 2022

Comments

  • ilyo
    ilyo almost 2 years

    When I have

    $('#div').click(function(someVar){//do something with soneVar});
    

    but I want to have a named callback function, am I palcing the passed someVar correctly?

    $('#div').click(someFunction(someVar));
    function someFunction(someVar){}