Reputation: 1509
How can I access a delegated object inside a delegate event handler? Hopefully an example should clarify my vague question.
$parent.delegate('a.some_class', 'click', someHandler);
function someHandler(e) {
//how do I find $parent here?
}
This is partly down to how I've structured my particular .js file, where declarations are separate from implementation (yeah, old skool I know).
In someHandler, e.target and $(this) refer to the a.some_class object. Does e also have a reference to $parent? If not, what is the recommended way of finding the $parent?
Thanks for any help.
Upvotes: 1
Views: 1423
Reputation: 1907
Jens Roland is correct. To add, the e.currentTarget should have given you the $parent where the event is actually handled. There's a bug that explains why currentTarget is not working the way it's supposed to http://bugs.jquery.com/ticket/11756
Upvotes: 1
Reputation: 27770
UPDATE: There is a way to grab the original element - e.originalEvent.currentTarget
:
$parent.delegate('a.some_class', 'click', someHandler);
function someHandler(e) {
var originalParent = $(e.originalEvent.currentTarget);
}
DEMO: http://jsfiddle.net/pjHQ6/
Original answer:
I'd probably do it like this:
$parent.delegate('a.some_class', 'click', someHandler);
function someHandler(e) {
var parent = $(this).parent();
// Or if $parent isn't the immediate ancestor of the links:
var parent = $(this).closest('.parentClass');
}
Upvotes: 4
Reputation: 1509
Stupid me. Should have read the jQuery docs better.
This should do it:
$parent.delegate('a.some_class', 'click', $parent, someHandler);
function someHandler(e) {
var parent = e.data;
}
e.data (in SomeHandler) always points to eventData, if using this delegate call.
.delegate( selector, eventType, eventData, handler )
Hope this helps someone.
Upvotes: 2