TIL Event Delegation
POSTED ON:
TAGS: javascript optimization events
Event delegation is one of the most helpful patterns for DOM events!
Adding too many event listeners means JavaScript is storing it all in memory.
Event Delegation lets you store one listener, that then looks for the target.
How to: #
- Put a single handler on the container.
- In the handler – check the source element event.target.
- If the event happened inside an element that interests us, then handle the event.
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.
Limitations: #
- the event must be bubbling. Some events do not bubble. Also, low-level handlers should not use event.stopPropagation().
- the delegation may add CPU load, because the container-level handler reacts on events in any place of the container, no matter whether they interest us or not. But usually the load is negligible, so we don’t take it into account.
via Event delegation
Related TILs
Tagged: javascript