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:
- allowing handlers to work on elements that have not yet been created/inserted into the DOM.
- binding one function to a common ancestor element rather than to multiple sibling elements
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?
live
handlers are different – Dott$('#el').delegate('a[href^=http://www.google.com]', 'click', func)
The selectora[href^=http://www.google.com]
will be run against the target of every click event that reaches#el
, I believe. – Peaked