Typically, when needing to access an event, you do so via 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 get into here), I do not want to use an anonymous callback function, but instead specify a function to call, like this:
$button.live("click", functionToCall(ev, $(this));
So you'll notice that I included 'ev' as a parameter to functionToCall(), but this obviously won't work because I'm not using the anonymous callback function. But I do still need to access that click event (to check ev.target) within functionToCall(). 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 very much appreciated. Thanks.
function test(eve) {
alert(eve.type);
alert(this);
//$(this) if you need it as jQuery object
}
$([yourselector]).live("click", test);
You will automatically get the event in the eve
parameter.
Passing in a parameter makes it a little more difficult. 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]));
You could call a function within the anonymous callback function:
$button.live("click", function(ev) {
functionToCall(ev, $(this));
}
EDIT: I think this may be what you're looking to do (untested):
function handleClick(ev) {
$(this).die("click");
// ...whatever processing to do...
$(this).live("click", handleClick);
}
$button.live("click", handleClick);
I believe the $(this) will refer to the button object in which the function was called.
Remember that jQuery re-assigns this
when it calls event handlers, by using the Function methods call or apply. So when functionToCall is invoked, this
is the DOM element of $button.
var functionToCall(ev) {
var $this = $(this);
$this.die("click", functionToCall);
// stuff
$this.live("click", functionToCall);
}
$button.live("click", functionToCall);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With