{"id":720,"date":"2009-02-19T22:47:44","date_gmt":"2009-02-20T03:47:44","guid":{"rendered":"http:\/\/unitstep.net\/?p=720"},"modified":"2009-02-20T22:54:03","modified_gmt":"2009-02-21T03:54:03","slug":"javascript-event-delegation","status":"publish","type":"post","link":"https:\/\/unitstep.net\/blog\/2009\/02\/19\/javascript-event-delegation\/","title":{"rendered":"JavaScript Event Delegation"},"content":{"rendered":"

JavaScript Event Delegation is a technique you may have heard of<\/a>. It’s a different way of using event handlers that offers clear benefits and is becoming more popular amongst web developers. I’ll give a brief overview of event delegation in JavaScript, along with why you should consider it. Note that this tutorial will use the great jQuery<\/a> library (v. 1.3.1) for most examples.<\/p>\n

Delegation<\/h3>\n

Delegation<\/a> is a fairly well-known design pattern. In short, it is a way for a method to produce its result simply by calling a method on another object, thus delegating<\/em> responsibility to that object to provide the functionality needed by the method. For example, a Cashier<\/code> object could store a delegate object called Calculator<\/code>. Calling Cashier.addToTotal(value)<\/code> would simply delegate to the contained object, calling Calculator.addToTotal(value)<\/code>. <\/p>\n

How is delegation different than inheritance<\/em>? With inheritance, the subclass inherits all of the functionality\/behaviour of the parent class. You may not want or need this; in the preceding example, it would not make sense to have Cashier<\/code> extend from Calculator<\/code> simply because we wanted the addToTotal()<\/code> behaviour\/functionality. Delegation allows the behaviour advertised by a certain object\/class to be provided by another.<\/p>\n

<\/p>\n

Traditional Event Handling<\/h3>\n

In order to understand event delegation in JavaScript, we should first look briefly at how events are handled traditionally. When I talk of traditional event handling<\/em>, I am referring to the model that most will know. In this model, functions are individually<\/strong> bound to events of certain elements. For example, to make all links turn bold upon clicking them (and prevent them from being followed), we could use some JavaScript like this:<\/p>\n

window.onload = function()\r\n{\r\n  links = document.getElementsByTagName('a');\r\n  for (var i = 0; i < links.length; ++i)\r\n  {\r\n    links[i].onclick = makeBold;\r\n  }\r\n\r\n}\r\n\r\nfunction makeBold()\r\n{\r\n  this.style.fontWeight = 'bold';\r\n  return false;\r\n}<\/code><\/pre>\n

The key point with this example is that the function makeBold()<\/code>, our event handler<\/em>, is bound to each and every<\/strong> a<\/code> element. From a resource point of view, this is may be a bad thing because the more event handlers that are attached, the more memory that is used, in general.<\/p>\n

Of course, I promised I’d be using jQuery, and doing so cleans up the above code substantially, as well as making it cross-browser compatible: (Besides adding a ton of other abilities and making life easier)<\/p>\n

jQuery(function()\r\n{\r\n  jQuery('a').click(makeBold);\r\n});\r\n\r\nfunction makeBold(e)\r\n{\r\n  e.preventDefault();\r\n  jQuery(this).css('font-weight', 'bold');\r\n}<\/code><\/pre>\n

While this code is cleaner, it still does basically the same thing as above, that is, the event handler function makeBold()<\/code> is bound to each<\/strong> matched element, that is, each a<\/code> element.<\/p>\n

As a final note, don’t confuse my use of the term traditional<\/em> with Peter-Paul Koch’s<\/a> excellent guide to JavaScript event registration, where he uses the term traditional<\/em> to refer to one method<\/em> of event registration<\/a>, distinct from inline registration and the later W3C<\/acronym><\/a> and Microsoft “Advanced” event registration models.<\/p>\n

Event handling using delegation<\/h3>\n

By contrast, event delegation<\/strong> uses a single (or comparatively few) event handlers to implement the behaviour required. This takes advantage of two key features of JavaScript events, namely event bubbling<\/a><\/strong> and the target event<\/a><\/strong>.<\/p>\n

Event bubbling<\/strong> is a model for how events take place on the page. It grew out of a need to resolve the order in which events were triggered on ancestor and descendant elements. For example, assume that I have two event handlers, one attached to the “click” event of a div<\/code> and another attached to the “click” event of an a<\/code> element within<\/strong> that div<\/code>. If I click the a<\/code> element, which event fires first? Event bubbling is one way to solve that question: It states that the event on the inner<\/strong> element happens first<\/em>, and then the event “bubbles” upwards to trigger events on ancestor or container elements. There is another opposing model that works in the opposite way, but bubbling seems to be better supported and is more relevant for this article.<\/p>\n

Here’s a crude diagram of event bubbling, using a pseudo-CSS<\/acronym> box model<\/a> of sorts:<\/p>\n

\n\"Event
\nEvent bubbling diagram\n<\/p>\n

The event target<\/strong> is the DOM element that issued the event, or the originating element. This is why I believe it’s a confusing term, since it would make more sense to called it the event source<\/em>. But I digress. The event object<\/a>, passed to an event handler as an argument (or available via window.event<\/code>, though jQuery normalizes this) contains a property, event.target<\/code>, that allows you to get the reference to the “target” element that the event started bubbling up from.<\/p>\n

How it’s implemented<\/h3>\n

All of this is typically accomplished by registering a single event handler to a “container” element that holds all of the elements we wish to react to events for. When an event is triggered on one of the inner elements, it “bubbles up” to the container element, where it triggers the event handler function. From there, we can inspect the source of the event (confusingly called the event target<\/em>) and then react accordingly.<\/p>\n

This is where the delegation aspect comes into play. Since the container element may hold many inner elements, it is unlikely that we would want the same behaviour for each element when an event was triggered on it. For example, we might want certain a<\/code> elements to trigger one action when clicked, while wanting another set of a<\/code> elements to trigger another action. We’d typically differentiate these links by using separate class names or by context and then attaching event handlers as appropriate.<\/p>\n

Using event delegation, process is similar, but instead of attaching multiple event handlers we have one on the overall parent element. When this event handler is triggered, we determine which element triggered the event and then based on this, delegate the remainder of the processing to another function. An example would be helpful now, as our previous examples with making some text bold weren’t too useful. Here’s the XHTML<\/acronym><\/a> fragment for the container and elements.<\/p>\n

<div class=\"container\">\r\n<ul class=\"top\">\r\n  <li>\r\n    <a href=\"#\" class=\"expandList\">Item A - Click to toggle<\/a>\r\n    <ul class=\"hide\">\r\n      <li>Sub-item 1<\/li>\r\n      <li>Sub-item 2<\/li>\r\n    <\/ul>\r\n  <\/li>\r\n  <li>\r\n    <a href=\"#\" class=\"expandList\">Item B - Click to toggle<\/a>\r\n    <ul class=\"hide\">\r\n      <li>Sub-item 1<\/li>\r\n      <li>Sub-item 2<\/li>\r\n    <\/ul>    \r\n  <\/li>\r\n  <li><a href=\"#\" class=\"remove\">Item C - Click to remove<\/a><\/li>\r\n  <li><a href=\"#\" class=\"remove\">Item D - Click to remove<\/a><\/li>\r\n<\/div><\/code><\/pre>\n

And here’s the JavaScript:<\/p>\n

jQuery(function()\r\n{\r\n  jQuery('div.container').click(handleEvent);\r\n});\r\n\r\nfunction handleEvent(e)\r\n{\r\n  \/\/ Obtain the source element through event.target.\r\n  var target = jQuery(e.target);\r\n  \r\n  \/\/ Now decide what to do with it.\r\n  if (target.is('a.expandList'))\r\n  {\r\n    \/\/ We use Function.call() to set the context for the `this` keyword.\r\n    return expandList.call(target, e);\r\n  }\r\n  else if (target.is('a.remove'))\r\n  {\r\n    return remove.call(target, e);\r\n  }\r\n  else\r\n  {\r\n    \/\/ Otherwise, allow the default action to take place.\r\n    return true;\r\n  }\r\n}\r\n\r\nfunction expandList(e)\r\n{\r\n  e.preventDefault();\r\n  \r\n  \/\/ The `this` keyword now references the jQuery object representing the \r\n  \/\/ target, since that is what we set the context to.\r\n  jQuery(this).parent('li').find('ul.hide').slideToggle('fast');\r\n}\r\n\r\nfunction remove(e)\r\n{\r\n  e.preventDefault();\r\n  jQuery(this).parent('li').fadeOut('normal', function(){jQuery(this).remove()});\r\n}<\/code><\/pre>\n

With this example, the steps are clearly outlined. First, we attach the overall event handler to the container element; events that take place on its inner or children element will bubble up to it. When an event is received, we inspect event.target<\/code> to determine the origin and based on that, “hand off” to another function to carry out the proper behaviour. <\/p>\n

With some standardization of the CSS<\/acronym> class names you use and the associated event handler function names, you can clean up this code to reduce duplication and turn it into a design pattern of sorts. In fact, that’s exactly what Dan Webb has done<\/a>.<\/p>\n

More advantages of event delegation<\/h3>\n

Besides potentially using less resources by having less event handlers bound, event delegation brings one other significant advantage: The ability to have event handlers “auto bind” to new DOM elements<\/strong>. For example, let’s say we were to dynamically update the DOM and add more list items to our previous example; this sort of action happens frequently during Ajax operations where you want to present new content to the user. <\/p>\n

In the “traditional” event handling model, the new elements would not automatically respond to events<\/strong> as you would like. This is because the events were individually bound to each element. This is a well known problem<\/a>. However, in event delegation, since there’s only one event handler bound to the container or ancestor element<\/strong>, the newly-created elements will respond to the event properly! This is because an event on them “bubbles” up to the container element just as for the original elements.<\/p>\n

Demo of Event Delegation<\/a><\/h3>\n

Perhaps a little demo<\/a> is needed. With this demo, you can see both the implementation of event delegation as well as the effect of adding new elements.<\/p>\n

Drawbacks of event delegation<\/h3>\n

I’ve already talked about some of the benefits (fewer bound event handlers, so less resources used and the ability to adapt with DOM changes), but it’s worthwhile to iterate over some of the drawbacks. <\/p>\n

    \n
  1. Firstly, not all elements “bubble up” in the way described. The blur<\/code>, focus<\/code>, change<\/code> and submit<\/code> are notable exceptions so you will not be able to use event delegation with these events in the manner described in this article.<\/li>\n
  2. Furthermore, the code developed to maintain event delegation can be more complicated to understand than with just using the traditional model. Indeed, there is an initial investment time everyone must make to get going. This should obviously be considered since code maintenance is always important.<\/li>\n
  3. Because there’s one event handler being called for all events on inner\/descendant elements, there can be some performance implications. If you’re calling expensive functions within this event handler, the event processing could slow down significantly. Careful optimization may be required.<\/li>\n<\/ol>\n

    However, some of these drawbacks can be mitigated by using solutions developed by the jQuery community. Even though event delegation is somewhat new, there are already plugins available that take a lot of the grunt-work out of event delegation, abstracting away the details and making things easier for you. Even jQuery itself also supports event delegation through a built-in function as of v1.3. Here are some options for pre-built solutions:<\/p>\n