Is it possible to pass a javascript function with arguments as an argument?
Example:
$(edit_link).click( changeViewMode( myvar ) );
Is it possible to pass a javascript function with arguments as an argument?
Example:
$(edit_link).click( changeViewMode( myvar ) );
This is an example following Ferdinand Beyer's approach:
function function1()
{
function2(function () { function3("parameter value"); });
}
function function2(functionToBindOnClick)
{
$(".myButton").click(functionToBindOnClick);
}
function function3(message) { alert(message); }
In this example the "parameter value" is passed from function1 to function3 through function2 using a function wrap.
Use Function.prototype.bind()
. Quoting MDN:
The
bind()
method creates a new function that, when called, has itsthis
keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
It is supported by all major browsers, including IE9+.
Your code should look like this:
$(edit_link).click(changeViewMode.bind(null, myvar));
Side note: I assume you are in global context, i.e. this
variable is window
; otherwise use this
instead of null
.
Use a "closure":
This creates an anonymous temporary function wrapper that knows about the parameter and passes it to the actual callback implementation.