How to access jQuery event without using an anonymous callback parameter

As a rule, if you need access to the event, you do this through the parameter specified in the callback function:

$button.live("click", function(ev) { // do something with ev here, like check 'ev.target' } 

But instead (for reasons too complicated to enter here), I don’t want to use an anonymous callback function, but instead specify a function to call, for example:

 $button.live("click", functionToCall(ev, $(this)); 

So, you will notice that I have included "ev" as a parameter to functionToCall (), but this obviously will not work, because I do not use the anonymous callback function. But I still need to access this click event (to check ev.target) in functionToCall () function. My question is: how do I access this event? It would be nice if I could do something like this:

 $button.live("click", functionToCall($(this)); 

and

 function functionToCall($item) { var target = $item.event("click").target; // do something with target } 

Any ideas would be greatly appreciated. Thanks.

+7
javascript jquery events parameters anonymous-function
source share
4 answers

Original answer

 function test(eve) { alert(eve.type); alert(this); //$(this) if you need it as jQuery object } $([yourselector]).live("click", test); 

You will automatically receive the event in the eve parameter.


The answer to the extended question in the comment

Passing a parameter makes it a little harder. If you need an explanation why I did it like this: ask.

 function helper(customparam) { return function(eve, selector) { actualFunction(eve, selector, customparam, this) }; } function actualFunction(eve, selector, customparam, self) { alert(eve.type); alert(selector); alert(customparam); alert(self); //self is now the element we clicked on //$(self) if you need it as jQuery object //using this won't work anymore as this is now window } $([yourselector]).live("click", helper([yourparameter])); 
+14
source share

You can call the function in an anonymous callback function:

 $button.live("click", function(ev) { functionToCall(ev, $(this)); } 

EDIT : I think this may be what you want to do (untested):

 function handleClick(ev) { $(this).die("click"); // ...whatever processing to do... $(this).live("click", handleClick); } $button.live("click", handleClick); 

I believe that $ (this) will refer to the button object in which the function was called.

+2
source share

Remember that jQuery reassigns this when it invokes event handlers using Function call or apply methods. Therefore, when functionToCall is called, this is a DOM element of the $ button.

 var functionToCall(ev) { var $this = $(this); $this.die("click", functionToCall); // stuff $this.live("click", functionToCall); } $button.live("click", functionToCall); 
+1
source share
 var mythis = $(this); var callback = function(ev) { var target = mythis.event("click").target; } $button.live("click", callback); 
0
source share

All Articles