Explain event delegation
Event delegation is the idea that something other than the target of an action resolves the event raised by that action. An example of event delegation would be having the document element handle the click action of a button. A fairly common occurrence, is to have a “ul” element handle the events raised by its children “li” elements.
Event delegation can be handled in several ways. The standard way is derived from native browser functionality. Browsers are programmed to handle events in a particular work flow. They are designed to support event capturing and event bubbling. The W3C documentation on how browsers are to support events can be found here:W3C DOM Level 3 Events. Some JS libraries and frameworks expose additional options such as the pub/sub model (which we will look at below).
Event capturing and event bubbling are two phases in a three phase flow. Any event that occurs, such as clicking a button, starts at the topmost container (which usually is the html root node). The browser moves down the DOM hierarchy until it finds the element raising the event. Once the browser finds the element that caused the event, it enters the targeting phase. Once targeting is complete, the browser bubbles up the DOM back to the topmost container to see if anything else needs to use the same event.
The fiddle below illustrates the process. Clicking on either button will cause the event flow to identify itself in the text below the container box. Each element receives the same click listener code. The click event first fires at the html node with the capturing phase, and then returns to the top at the end of the bubble phase.
[iajsfiddle user=”dposin” fiddle=”exuufg7a” height=”300px” width=”100%” show=”js,html,result” skin=”default”]
Most modern libraries use the bubble phase for listener handling over the capture phase. Browsers include a way to manage how high we want the event to bubble. An event handler can call stopPropagation to tell the event to cease bubbling up the DOM. There is a second option called stopImmediatePropagation. This method stops the bubbling, and will also stop any other listeners for this event on this element from firing. However, be careful when stopping propagation since you don’t really know if there is anything else up the DOM that might want to be aware of the event.
There is a third function worth knowing that can be called to control how elements react to events. All modern browsers support the preventDefault function. This function prevents the browser from using its native operations to handle the event. A common use case is the link. Using links to perform UI operations is a common practice. However, we don’t want that link to try activating the regular link function of opening the page to a new page. Using preventDefault stops the browser from trying to follow an href tag.
There are other delegation methods to consider as well. One worth mentioning here is the pub/sub model. The publication/subscription model, also called a radio model, involves two participants. Usually, the two participants are not closely connected in the DOM, and may actually be derived from sibling containers. One could put a listener on the element they both ultimately descend from, but if the shared ancestor element is very high then you could end up listening for too many events at that level and create the dreaded monolith mentioned earlier. Also, there may be logically or architectural reasons to keep the two elements separate.
The Pub/Sub model also opens the opportunity to create custom events. The pub/sub model works by sending a message out from one element and traveling up, and sometimes down, the DOM telling all elements along the way that the event happened. jQuery uses the trigger function to pass events up the DOM as illustrated in the fiddle below.
[iajsfiddle user=”dposin” fiddle=”7983sjk7″ height=”300px” width=”100%” show=”js,html,result” skin=”default”]
The are several benefits of using event delegation to manage the event flow. One of the biggest is performance. Every listener attached to an element takes up some memory. If there are only a few listeners on a page then the difference won’t be noticed. However, if you have a listener on every cell of a 50 row 5 column table then your web application may begin to slow down. In the interest of making an application as fast as possible it is best to keep memory use as low as possible.
Using event delegation can reduce the number of listeners from many to a few. Placing a listener on a container above the elements firing the event means only needing one listener. The drawback to this approach is that the listener at the parent container may need to examine the event to choose the correct operation, whereas a listener on the element itself would not. The impact of that extra processing is much less than the impact of too many listeners in memory.
Fewer listeners and fewer points of DOM interaction make for easier maintenance. One listener at a container level can handle multiple different event operations. This is not an excuse for a monolithic function of titanic proportions. It is an easy way to manage related events that often perform related functions or need to share data.
If a parent container is listening then individual operations performed inside that container don’t have to add or remove listeners on their own. Operations like dynamic buttons and elements are extremely common with the increased use of single page applications. Something as simple as adding a button dynamically to a section can create a potential performance block for your application. Without proper event delegation it becomes necessary to manually add listeners to each new button, and if each listener is not cleaned up properly, it can potentially cause memory leaks. The browser does not clear the page, and therefore memory, in a single page application so everything that is not cleaned from memory properly can stick around. These fragments in memory drag down the performance of your application, like a great sponge that continues to absorb memory growing heavier and bigger and never releasing the pent-up memory.
When adding interaction to your pages, do yourself (and the person maintaining your code in the future) a favor, and carefully consider which element really needs to be listening.
Additional Articles Worth Reading
- If “this” has not been set to anything then it defaults to the global object, which is usually Window.
- If a function is running on an in-line function, such as an event listener, then “this” will refer to the source of the function. For example, when setting a click handler for a button, “this” will refer to the button inside the anonymous function.
- If a function is a constructor for an object, then this will refer to the new object.
- If a function is being defined on an object, then when invoked on the object, “this” will refer to the object.
In a world of asynchronous programming and the helpful existence of promises, it is easy for “this” to change in the course of one feature’s operation. One trick to keep a handle on the context that started the operation is to set it to a variable inside a closure. When you call a function where context changes, like setTimeout, you will still be able to reference the object you need through that variable.
The other way one can manipulate “this” is through the use of call, apply, and bind. All three of these methods are used to invoke a function with a specific context of “this”. Instead of relying on the browser operation to figure out what “this” is, you can tell the code to use the object you are proposing. Call, apply, and bind can be pretty sophisticated in their own right and deserve their own writeup. We will address them in a future installment. An example of the many changing ways of “this” is below:
[iajsfiddle user=”dposin” fiddle=”okjr81ev” height=”300px” width=”100%” show=”js,html,result” skin=”default”]