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)
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
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