Passing a function with parameters as a parameter?
Solution 1:
Use a "closure":
$(edit_link).click(function(){ return changeViewMode(myvar); });
This creates an anonymous temporary function wrapper that knows about the parameter and passes it to the actual callback implementation.
Solution 2:
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
.
Solution 3:
No, but you can pass one without parameters, and do this:
$(edit_link).click(
function() { changeViewMode(myvar); }
);
So you're passing an anonymous function with no parameters, that function then calls your parameterized function with the variable in the closure
Solution 4:
Or if you are using es6 you should be able to use an arrow function
$(edit_link).click(() => changeViewMode(myvar));
Solution 5:
Yes, like this:
$(edit_link).click(function() { changeViewMode(myvar) });