Using bind (type, [data], fn) and non-inline function

$("p").bind("click", function(event){
       // code goes here
});

      

This is understandable. But what is the way to use a non-inline function and pass the event as an argument? I.e:

$("p").bind("click", myFunction(event));

 function myFunction(event) {
       // code goes here
 }

      

Thanks!

+1


a source to share


3 answers


Here:



$("p").bind("click", myFunction);

function myFunction(event) {
    // code goes here
}

      

+3


a source


Your problem is that you are giving it an argument that causes the function to execute and the return value is replaced as the argument for the binding. What you want to do is just provide a reference to the function as an argument for the binding. Do this, leaving out the parentheses (and the argument). The arguments supplied by the binding to the callback must be included in the function definition.



$("p").bind("click", myFunction);

function myFunction(event) {
    // code goes here
}

      

+2


a source


So when you do something like

$('p').bind('click', myFunction(event);

function myFunction(event){
//code
}

      

It looks like if you create your own "event object" instead of using the generated jQuery, when does the user action happen?

0


a source







All Articles