Reading another Stack Overflow question about jQuery performance, I started thinking about the point when it becomes worth using event delegation rather than binding to elements individually. I was thinking mainly about jQuery, but I suppose it is probably applicable for Javascript in general.
Event delegation has two main purposes:
My question is about the second of these. The general answer will probably be "it depends on the exact situation", but I wonder if there is a rule of thumb or a way of benchmarking in order to test this.
So, the question is: how many elements do you need before the performance benefits of event delegation outweigh the performance costs?
Event delegation refers to the process of using event propagation (bubbling) to handle events at a higher level in the DOM than the element on which the event originated. It allows us to attach a single event listener for elements that exist now or in the future.
Benefits: Simplifies initialization and saves memory: no need to add many handlers. Less code: when adding or removing elements, no need to add/remove handlers. DOM modifications: we can mass add/remove elements with innerHTML and the like.
tl;dr: event delegation is the technique, bubbling is what the event itself does, and capturing is a way of using event delgation on events that don't bubble.
Assuming this HTML structure:
<ul id="navUL">
<li><a href="one.html">One</a></li>
<li><a href="two.html">Two</a></li>
<li><a href="three.html">Three</a></li>
</ul>
Just to clear things up (for me) .... According to jQuery docs ( http://api.jquery.com/delegate/ ), this:
$("#navUL").delegate("a", "click", function(){
// anchor clicked
});
... is equivalent to this:
$("#navUL").each(function(){
$("a", this).live("click", function(){
// anchor clicked
});
});
However, event delegation (as I know it) is this:
$("#navUL").click(function(e) {
if (e.target.nodeName !== "A") { return false; }
// anchor clicked
// anchor is referenced by e.target
});
So you catch the click event on the UL element, and then figure out which anchor was actually clicked via the event.target
property.
I don't know about the delegate() method, but this last technique should always be faster than attaching event handlers to each anchor in the #navUL element, like so:
$("#navUL a").click(function() {
// anchor clicked
// anchor is referenced by the this value
});
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