Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

the right way to pass variable to a callback function [duplicate]

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){}
like image 812
ilyo Avatar asked Dec 04 '22 21:12

ilyo


1 Answers

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); });
like image 65
SLaks Avatar answered Dec 07 '22 09:12

SLaks