Optimizing event listeners through event delegation
Event delegation is a common event listener pattern used to go from “many elements, many event listeners” to a “many elements, single event listener.” At its core, event delegation attaches one event listener to the page’s Document
, and inside that listener, it checks what the target
of the event is in order to figure out how the event should be handled.
Event delegation means fewer listeners are attached. There’s only one per root node; if we’re doing event delegation at the document level, that means one listener. Another benefit is that DOM nodes can be attached and removed without worrying about adding or removing the relevant event listeners.
The following sequence diagram details an implementation of listening to clicks on two buttons.
Figure 8.1: Event handling without event delegation
Event handling without event delegation can be contrasted...