Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function as method argument in jquery without writing the entire function definition

From what i understand, in jquery, when a method requires a function as an argument you can't just invoke a predefined function like this:

$('#target').click(myFunction());

...because "myFunction()" will be parsed and replaced with the value returned by the function...which is no longer a function.You have to put the entire function definition, in an anonymous function:

$('#target').click(function() {
   alert('Handler for .click() called.');
});

...so, is there any way of just invoking the function where it's required as an argument?

like image 372
bogdan Avatar asked Mar 22 '26 17:03

bogdan


2 Answers

You understand correctly. It is true not only in jQuery, this is how JavaScript works. When a function is needed as an argument, then you have to give a function as an argument, and not the result of its invocation. You can use this:

$('#target').click(myFunction);

but for alert you need an anonymous function because you are passing an argument.

like image 175
rsp Avatar answered Mar 25 '26 07:03

rsp


You are passing the result of the function, not the function itself. Instead of:

click(myFunction());

use

click(myFunction);

Live example on jsfiddle.

like image 43
Andomar Avatar answered Mar 25 '26 05:03

Andomar