Today I Learned - Rocky Kev

TIL Event Delegation

POSTED ON:

TAGS:

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:

  1. Put a single handler on the container.
  2. In the handler – check the source element event.target.
  3. If the event happened inside an element that interests us, then handle the event.

Benefits:

  1. Simplifies initialization and saves memory: no need to add many handlers.
  2. Less code: when adding or removing elements, no need to add/remove handlers.
  3. DOM modifications: we can mass add/remove elements with innerHTML and the like.

Limitations:

  1. the event must be bubbling. Some events do not bubble. Also, low-level handlers should not use event.stopPropagation().
  2. 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:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.