Anyone who has spent a long time building JavaScript applications knows how important event handlers can be for processing certain common user actions, such as mouse clicks, windows and keyboard events, and so forth. However, while event handlers are a powerful feature for creating highly responsive JavaScript programs with relative ease, they have been overused way too frequently. This has implications for how quickly certain kinds of JavaScript programs run. Fortunately, JavaScript event delegation can help solve many of these problems. This four-part series explains how.
Many web designers now implement event handlers more carefully, and resist the temptation to fire up functions and classes each time users click on different elements across a web page.
Regardless of this promising scenario, it’s common to see JavaScript programs that use event handlers in a poor and inefficient way. Let me explain this concept a bit further with an example: suppose for a moment that there’s a server-side application that pulls a product catalog from a database table and displays its contents via a typical HTML table.
So far, so good, right? Now, it’s possible to extend the behavior of this application with some unobtrusive JavaScript and assign a click event handler to each cell of the table, so every time a user clicks on a product item, a tooltip will be displayed showing some additional information about that product. Simple and effective, right?
Well, unfortunately, that’s really not so effective. Considering that this HTML table might be populated with tens of products items, in theory the same number of click handlers should be assigned to each table cell. This could consume a lot of RAM. Naturally, for small machines this heavy load might cause system hang-ups or, in the best case, browsers running very slowly.
So, how do we solve this issue efficiently and elegantly? The answer is simply with JavaScript event delegation. As you know, events have two different phases, called “capture” and “bubble” respectively. Thus, returning to the previous example, it’d be feasible to assign only one click handler to the whole HTML table, and then by using the bubbling phase, to determine what cell was clicked by the user.
This process is known popularly as event handling delegation, and in this group of articles, I’ll be coding some concrete examples that will help you grasp how it works, so you can implement it within your own JavaScript programs.
Now that you’ve digested the theory behind using event delegation in JavaScript, it’s time to learn how to take advantage of it with functional code samples. Ready? Then let’s get started!