CINXE.COM
Event Listeners: Delegation VS Direct Binding - JASON Format
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Event Listeners: Delegation VS Direct Binding - JASON Format</title> <meta name="viewport" content="width=device-width,initial-scale=1"> <link rel="icon" href="/assets/icon.png"> <link rel="modulepreload" as="script" href="/index.2b1d13e1.js" crossorigin="anonymous"> <link rel="stylesheet" href="/assets/styles/index.58f97fe6.css"> <link rel="alternate" type="application/rss+xml" title="Jason Format" href="/posts.rss"> <link rel="me" href="https://mastodon.social/@developit"> <link rel="me" href="https://toot.cafe/@developit"> </head> <body><div class="app"><header class="header_limv23"><nav><a href="/"><img src="/assets/icon.png" class="logo_limv23" title="Home" /></a><a href="/blog">Blog</a></nav><nav class="right_limv23"><a href="https://twitter.com/_developit" target="_blank" rel="noopener" title="Twitter"><svg width="24" height="24" viewBox="0 0 24 24"><path d="M24 4.6c-.9.3-1.8.6-2.8.7a5 5 0 002.1-2.7c-1 .6-2 1-3 1.2a5 5 0 00-8.5 4.5A14 14 0 011.7 3a5 5 0 001.5 6.6c-.8 0-1.6-.2-2.2-.6A5 5 0 005 14a5 5 0 01-2.3 0 5 5 0 004.6 3.5 9.9 9.9 0 01-7.3 2A14 14 0 0021.5 7.1 10 10 0 0024 4.6z"></path></svg></a><a href="https://github.com/developit" target="_blank" rel="noopener" title="GitHub"><svg width="24" height="24" viewBox="0 0 24 24"><path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z"></path></svg></a><input class="dark_limv23" type="checkbox" title="Dark Mode" /></nav></header><div class="post"><div class="post-meta"><img src="https://res.cloudinary.com/wedding-website/image/upload/v1598628155/nasa-Q1p7bh3SHj8-unsplash_inzedd.jpg" alt decoding="async" /><h1>Event Listeners: Delegation VS Direct Binding</h1><time title="Fri Aug 28 2020 11:00:15 GMT+0000 (Coordinated Universal Time)">Aug 28, 2020</time></div><div class="content md"><div> <img src="https://res.cloudinary.com/wedding-website/image/upload/v1598628155/nasa-Q1p7bh3SHj8-unsplash_inzedd.jpg"> <figcaption style="position:relative;top:-1em;text-align:right;font-size:70%;"><a href="https://unsplash.com/photos/Q1p7bh3SHj8" target="_blank" style="color:#999;text-decoration:none;">Image courtesy of NASA</a></figcaption> </div> <p>The DOM provides a mechanism for registering event handlers that supports two techniques for observing events: directly-bound per-element listeners, <em>and</em> “delegated” listeners that receive events originating from within an entire subtree.</p> <p>Frameworks and libraries that abstract event listener registration generally choose between the two approaches, yet this area of front-end performance has seen relatively limited debate. Library developers often rely on past experience to make decisions relating to event delegation vs direct binding, which I’ll try to summarize in this article.</p> <h3 id="direct-binding">Direct Binding</h3> <p>The oldest and simplest way to listen for DOM events is to register an event handler function directly on the node that will emit that event. Most DOM events propagate up the tree from their originating <code>target</code> Node, so this approach can be combined freely with delegation techniques (more on that later).</p> <p>Here’s a simple example of a directly bound event handler that intercepts clicks on a particular anchor link:</p> <pre><code class="language-html"><span class="token tag"><span class="token tag"><span class="token punctuation"><</span>a</span> <span class="token attr-name">href</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>/<span class="token punctuation">"</span></span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>home<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>Home<span class="token tag"><span class="token tag"><span class="token punctuation"></</span>a</span><span class="token punctuation">></span></span> <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>script</span><span class="token punctuation">></span></span><span class="token script"><span class="token language-javascript"> home<span class="token punctuation">.</span><span class="token function">addEventListener</span><span class="token punctuation">(</span><span class="token string">'click'</span><span class="token punctuation">,</span> <span class="token parameter">e</span> <span class="token operator">=></span> <span class="token punctuation">{</span> <span class="token keyword">const</span> link <span class="token operator">=</span> e<span class="token punctuation">.</span>currentTarget<span class="token punctuation">;</span> <span class="token comment">// <a></span> history<span class="token punctuation">.</span><span class="token function">pushState</span><span class="token punctuation">(</span><span class="token keyword">null</span><span class="token punctuation">,</span> <span class="token keyword">null</span><span class="token punctuation">,</span> link<span class="token punctuation">.</span>href<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token function">fancyPageLoad</span><span class="token punctuation">(</span>link<span class="token punctuation">.</span>href<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// "ajax"</span> e<span class="token punctuation">.</span><span class="token function">preventDefault</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// prevent page load</span> e<span class="token punctuation">.</span><span class="token function">stopPropagation</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span> </span></span><span class="token tag"><span class="token tag"><span class="token punctuation"></</span>script</span><span class="token punctuation">></span></span> </code></pre> <p>In the example, direct binding is accomplished easily because we already have a reference to the element on which the click event will be triggered. This is a case where direct binding is also the best approach from a performance standpoint, since no DOM tree traversal is required to register or handle the event. Strictly looking at our own logic, registering and invoking the listener are both <code>O(1)</code> operations.</p> <h3 id="event-delegation">Event Delegation</h3> <p>Event delegation is a technique for listening for events in the aggregate. It leverages the fact that most events “bubble” up the DOM tree, which means they can be intercepted at the tree’s root and handled there.</p> <p>One of the key features that makes event delegation valuable is that it is possible to handle events from any target node <em>without</em> having a prior reference to that node. In cases where an event handler needs to listen on a large or changing set of target nodes, this avoids having to manually manage adding and removing handlers from each node. </p> <p>Imagine our previous link click handling example, except now there are many links on the page, and additional links may be added or removed over time:</p> <pre><code class="language-html"><span class="token tag"><span class="token tag"><span class="token punctuation"><</span>a</span> <span class="token attr-name">href</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>/<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>Home<span class="token tag"><span class="token tag"><span class="token punctuation"></</span>a</span><span class="token punctuation">></span></span> <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>a</span> <span class="token attr-name">href</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>/profile<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>Profile<span class="token tag"><span class="token tag"><span class="token punctuation"></</span>a</span><span class="token punctuation">></span></span> <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>a</span> <span class="token attr-name">href</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>/search<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>Search<span class="token tag"><span class="token tag"><span class="token punctuation"></</span>a</span><span class="token punctuation">></span></span> <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>script</span><span class="token punctuation">></span></span><span class="token script"><span class="token language-javascript"> <span class="token keyword">function</span> <span class="token function">handleClick</span><span class="token punctuation">(</span><span class="token parameter">e</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> history<span class="token punctuation">.</span><span class="token function">pushState</span><span class="token punctuation">(</span><span class="token keyword">null</span><span class="token punctuation">,</span> <span class="token keyword">null</span><span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>href<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token function">fancyPageLoad</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>href<span class="token punctuation">)</span><span class="token punctuation">;</span> e<span class="token punctuation">.</span><span class="token function">preventDefault</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span> <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">let</span> link <span class="token keyword">of</span> document<span class="token punctuation">.</span><span class="token function">querySelectorAll</span><span class="token punctuation">(</span><span class="token string">'a[href]'</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> link<span class="token punctuation">.</span><span class="token function">addEventListener</span><span class="token punctuation">(</span><span class="token string">'click'</span><span class="token punctuation">,</span> handleClick<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span> <span class="token comment">// ...listen for added/removed links using MutationObserver...</span> </span></span><span class="token tag"><span class="token tag"><span class="token punctuation"></</span>script</span><span class="token punctuation">></span></span> </code></pre> <p>Implementing this using direct binding requires searching the DOM for anchorlink elements and registering event handlers on each. We’d also need to use something like <code>MutationObserver</code> to detect newly-added links and register our handler on them. This would be expensive, since searching the DOM incurs a runtime performance cost and increases memory usage, as does <code>MutationObserver</code>. Listener invocation has the same performance as the previous simple direct binding example, but registration no longer runs in constant time.</p> <p>Let's compare this to a solution using event delegation:</p> <pre><code class="language-html"><span class="token tag"><span class="token tag"><span class="token punctuation"><</span>a</span> <span class="token attr-name">href</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>/<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>Home<span class="token tag"><span class="token tag"><span class="token punctuation"></</span>a</span><span class="token punctuation">></span></span> <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>a</span> <span class="token attr-name">href</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>/profile<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>Profile<span class="token tag"><span class="token tag"><span class="token punctuation"></</span>a</span><span class="token punctuation">></span></span> <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>a</span> <span class="token attr-name">href</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>/search<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>Search<span class="token tag"><span class="token tag"><span class="token punctuation"></</span>a</span><span class="token punctuation">></span></span> <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>script</span><span class="token punctuation">></span></span><span class="token script"><span class="token language-javascript"> <span class="token function">addEventListener</span><span class="token punctuation">(</span><span class="token string">'click'</span><span class="token punctuation">,</span> <span class="token parameter">e</span> <span class="token operator">=></span> <span class="token punctuation">{</span> <span class="token keyword">let</span> target <span class="token operator">=</span> e<span class="token punctuation">.</span>target<span class="token punctuation">;</span> <span class="token keyword">do</span> <span class="token punctuation">{</span> <span class="token keyword">if</span> <span class="token punctuation">(</span>target<span class="token punctuation">.</span>localName <span class="token operator">===</span> <span class="token string">'a'</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> history<span class="token punctuation">.</span><span class="token function">pushState</span><span class="token punctuation">(</span><span class="token keyword">null</span><span class="token punctuation">,</span> <span class="token keyword">null</span><span class="token punctuation">,</span> target<span class="token punctuation">.</span>href<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token function">fancyPageLoad</span><span class="token punctuation">(</span>target<span class="token punctuation">.</span>href<span class="token punctuation">)</span><span class="token punctuation">;</span> e<span class="token punctuation">.</span><span class="token function">preventDefault</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token keyword">break</span><span class="token punctuation">;</span> <span class="token punctuation">}</span> <span class="token punctuation">}</span> <span class="token keyword">while</span> <span class="token punctuation">(</span>target <span class="token operator">=</span> target<span class="token punctuation">.</span>parentNode<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span> </span></span><span class="token tag"><span class="token tag"><span class="token punctuation"></</span>script</span><span class="token punctuation">></span></span> </code></pre> <p>Now our example uses a single delegated event handler, which removes all event handler management costs. There is a small performance tradeoff being made here, which is that the handler has to walk up the DOM tree to detect if a click occurred on a link. In this case our logic for registering the listeners is <code>O(1)</code>, and the listener's invocation is <code>O(log(n))</code>.</p> <p>In many cases where there’s a very large number of event targets or where event targets are not known up-front, event delegation can improve performance by relying on the browser’s hit testing logic to dynamically observe events of a given type.</p> <h3 id="event-delegation-can-be-tricky">Event delegation can be tricky</h3> <p>It’s important to note that event delegation can create a set of problems not found when using directly-bound event handlers. Delegation can make event “pathing” difficult, and the effects of this are sometimes only revealed as a codebase increases in complexity. One example of this occurs when the DOM tree is mutated during the course of an event’s capturing or bubbling phase: should an event continue bubbling if its target or an ancestor is removed?</p> <p>A concrete example of where event pathing grows difficult is handling events from other documents in a fully delegated event handling model. An event triggered within an iframe does not bubble up to the parent document, which means it cannot be handled via delegation. This can be addressed by adding additional delegated event handlers in documents, which can either handle or retarget/refire the event in the parent document to emulate bubbling. While edge cases like these are not always important to account for, if they become necessary it can complicate event delegation and reduce its performance value.</p> <h3 id="missing-out-on-features">Missing out on features</h3> <p>For those exploring event delegation, it’s important to take note of some direct binding features that are more difficult or even impossible to leverage in a delegated model. In the past few years, the <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener">addEventListener API</a> has gained support for one-time handlers that are automatically removed after being fired, which can help avoid a class of memory leak caused by DOM references retained solely to allow for listener removal.</p> <p>Passive listeners are another addEventListener feature introduced somewhat recently, offering a way to listen for events without blocking user interaction when they occur. This is an important technique to have at your disposal when implementing things like touch and scroll reactivity. Browsers are actively moving towards firing passive events by default, however this is happening slowly and on a case-by-case basis due to a high potential for breaking the web. Until this transition is complete, it’s a good idea to make sure your solution for delegating events provides a way to register passive listeners - or even uses passive listeners by default.</p> <p>Another feature that event delegation implementations sometimes struggle with recreating is the level of optimization already present in browser event implementations. Events are created and initialized at the root of a document and their hit-tested event path is constructed in advance despite its JavaScript representation being lazily-constructed. The same Event object instance is passed to each handler invoked during the capturing and bubbling phases. Browsers engines can optimize garbage collection of Event instances, since they do not have to hold a strong reference to an event. It should be possible to approximate these optimizations in a JavaScript implementation using recently-added language features like <a href="https://v8.dev/features/weak-references">WeakRef and Finalizers</a>, however it’s unlikely any popular solutions will leverage this for some time.</p> <p>Finally, one of the most compelling arguments in favor of directly binding event listeners rather than using global event delegation is interoperability. Event listeners registered directly on nodes are partaking in the DOM’s cooperative event handling model: every element and its listeners have a chance to observe or intercept events, and can participate in a shared decision on how a given event should be handled. This becomes apparent when combining multiple frameworks on a page - if each framework implements its own event propagation model using global delegated listeners, important event handling concerns like default behavior prevention and retargeting can become difficult or even impossible.</p> <h3 id="event-delegation-is-not-a-better-addeventlistener">Event delegation is not a better addEventListener</h3> <p>The tradeoff between direct binding and event delegation is hard to measure, which makes it difficult to clearly state which approach is better overall. As illustrated above, there are certainly cases where maintaining listeners across a set DOM nodes requires bookkeeping that incurs a performance penalty compared to event delegation. Using event delegation defers some of this cost so that it is paid as part of handling each event, which can be disadvantageous if event handling performance is paramount.</p> <p>One generalization that can guide the decision between these approaches is that direct binding is generally a better option if the code in question already has a stable reference to the DOM node on which an event will be fired. These are cases with inherently minimal bookkeeping cost, since the lifecycle of an event handler does not need to be manually managed. As a rule of thumb, if you don’t have to search for a node in order to attach an event handler to it, it’s likely a good case for binding directly.</p> <p>One concrete example of such a case is Preact’s event handler abstraction, which is often brought up when discussing the efficacy or delegated vs direct event handling. Preact’s renderer is already responsible for retaining a mirror tree in order to perform Virtual DOM diffing, which means there’s already <a href="https://github.com/preactjs/preact/blob/82bcc15638ce747b311c9bf1c6840b0640c75151/src/diff/props.js#L100-L109">a clear place</a> to perform direct event handler binding during updates. To minimize any invocation cost associated with <code>addEventListener()</code> and <code>removeEventListener()</code>, a single proxy listener is registered for all events that looks up the current listener for a given event when it is fired. This means “swapping” an event handler to a new function reference only updates the current handler reference and does not remove or re-add any event listeners.</p> <h3 id="you-dont-have-to-choose">You don’t have to choose</h3> <p>Ultimately, it’s best not to treat event delegation and direct binding as dichotomous. Both techniques have merit, and there are many cases where a combined solution offers the best performance or least complexity.</p> </div><footer><h5>There used to be comments here.</h5><p><null>Instead, </null><a href="https://mastodon.social/@developit">toot</a><null> or </null><a href="https://twitter.com/_developit">tweet me</a><null> your comments.</null></p></footer></div></div><script type="isodata"></script> <script type="module" src="/index.2b1d13e1.js" crossorigin="anonymous"></script> </body> </html>