Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantage of *this* over event.target

Is it better / faster inside an event listener to use this or event.target

I've been writing code like this (example is jQuery):

jQuery('input').bind('keyup', function (e) {
 var j = jQuery(e.target);
 foo(j.attr('id') , j.val() );
});

And I was told to replace e.target with this because it's "better". Is there really any advantage to one or the other?

I use target because it's a more general solution as it works for delegated events. I'm having trouble benchmarking because my tests get cluttered with the binding (Although, obviously, in this case the difference would be too small to matter anyway)

like image 372
ColBeseder Avatar asked Jul 03 '12 09:07

ColBeseder


2 Answers

The one isn't better than the other, but they do different things: this refers to the element the event is attached to, while event.target is the element that invoked the event.

For example

div id=foo   
   div id=bar

when click is attached to foo, and bar is clicked, the event will bubble up to foo. In the event this will refer to foo and event.target to bar

In the end it depends on which element you need to handle.

There's a small example on api.jquery.com/event.target that illustrates event.target. Here's a small sample that uses that example, but which also displays this: http://jsbin.com/adifan/edit#javascript,html,live

like image 86
Me.Name Avatar answered Oct 19 '22 05:10

Me.Name


Well, the jQuery documentation is clear about it :-)

The target property can be the element that registered for the event or a descendant of it. It is often useful to compare event.target to this in order to determine if the event is being handled due to event bubbling. This property is very useful in event delegation, when events bubble.

(Source: http://api.jquery.com/event.target/)

This link explains the term "event bubbling": http://www.quirksmode.org/js/events_order.html

like image 35
dmnkhhn Avatar answered Oct 19 '22 04:10

dmnkhhn