views:

262

answers:

3

Hi,

Is it possible to pass a javascript function with parameters as a parameter?

Example:

$(edit_link).click(changeViewMode(myvar));

Thanks.

+14  A: 

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.

Ferdinand Beyer
+1, most detailed answer
Adriano Varoli Piazza
+1  A: 

Yes, like this:

$(edit_link).click(function() { changeViewMode(myvar) });
Philippe Leybaert
+2  A: 

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

Clyde
typo: clicik
Adriano Varoli Piazza