Question

When is it better (performance/readability/optimal) to use delegation instead of attaching the handler directly to the element in question?

$(".container").on("click", "button", function(){});
$(".container button").on("click", function(){});
Was it helpful?

Solution 2

It depends on the number of click events that are bound inside the container.

$(".container button").on("click", function(){});

If there are only a few events happening and the button is already on the page the event bound by above signature should do the work for you.

$(".container").on("click", "button", function(){});

When a element is dynamically added to your page then use Event Delegation wherein normal binding of events will not work.

The performance question comes into play based on how heavy event driven your application is. Performance should not matter if that number is small. But lets say you have 1000 click events on the elements inside the container.

Would you create a click for all the common elements with the same functionality. In such cases you could use delegation, wherein the event will be attached to a single element, which can lead to less maintainable code and more readability.

OTHER TIPS

Delegation comes in handy when you might want to add more elements and have the listeners still work without adding them again. Perhaps you have dynamically created elements that need to have the same event listeners. I don't know the performance answer. I'm curious what others think!

In your example, if you added a new button to .container, the delegate model would allow the listener to work.

Event delegation is best for when the targeted elements are dynamic, meaning they don't exist at DOM ready, or their attributes change in ways that change which handlers should handle events on them.

It is also good for when you have a lot of elements to bind to. If you have a table with 1000 td elements, you can do a single event binding to the table, instead of 1000 to bind to each `td.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top