Is it possible to pass a javascript function with arguments as an argument?
Example:
$(edit_link).click( changeViewMode( myvar ) );
-
5It looks like JQuery, and most likely is, but that is irrelevant. The use or parameters and functions is the same regardless of what Javascript libraries you use.Guffa– Guffa2009年08月19日 14:18:32 +00:00Commented Aug 19, 2009 at 14:18
-
1If you are working with React, consider stackoverflow.com/questions/41369497/…Michael Freidgeim– Michael Freidgeim2020年02月03日 01:22:09 +00:00Commented Feb 3, 2020 at 1:22
7 Answers 7
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.
6 Comments
this.myFunction = this.myFunction.bind(this) in your constructor method. But, like you said, when you have to pass different contexts to it for each one, like all different rows that you click on to open that row's detail page, it's not avoidable.Use Function.prototype.bind(). Quoting MDN:
The
bind()method creates a new function that, when called, has itsthiskeyword 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.
4 Comments
$.ajax(url).done(handler.bind(this, var1, var2));fn.bind(this) to resolve the dreaded this confusion in callback functions without understanding the broader purpose of bind – but now I get it! Thanks 🙏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
Comments
Or if you are using es6 you should be able to use an arrow function
$(edit_link).click(() => changeViewMode(myvar));
Comments
Yes, like this:
$(edit_link).click(function() { changeViewMode(myvar) });
Comments
You can do this
var message = 'Hello World';
var callback = function(){
alert(this)
}.bind(message);
and then
function activate(callback){
callback && callback();
}
activate(callback);
Or if your callback contains more flexible logic you can pass object.
Comments
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.
Comments
Explore related questions
See similar questions with these tags.