Why to use DOM 2 event listeners?

document.getElementById("myButton").onclick = function(e) {
    //do something
};

What’s wrong with this approach of assigning handler to an event? If you ask me, I can think of at least 4 reasons not to follow it.

  1. It looks really ugly.
  2. If multiple programmers are working on the same interface, there might be situations you won’t be aware of other pre-existing event handlers to the same DOM element. The above method is a sure-shot way to override existing handlers.
  3. What if I want to have multiple handlers for the same event on a DOM element? Yes, with tricks it can be achieved (by retaining the existing event handler). But even a novice programmer can guess the trouble one can get into as the number of handlers goes on.
  4. Let’s assume you assign 5 event handlers using the above method to the same element. Now, you want to remove the third one (random). There is no way you can crack this without modifying all instances of event handler assignment.

So? This is exactly why DOM 2 events module introduced a standard and more manageable approach for assigning handlers to an event.

function attachEventListener(domElement, eventName, eventHandler) {
    if(window.addEventListener){        // Mozilla, Netscape, Firefox
        domElement.addEventListener(eventName, eventHandler, false);
    } else {                            // IE
        domElement.attachEvent("on" + eventName, eventHandler);
    }
}

Now,

var myButton = document.getElementById("myButton");
var myButtonClickHandler =
function(e) {//do something};
attachEventListener(myButton, "click", myButtonClickHandler);

Can an anonymous function be used here instead of a function reference? Not a good idea. If at a later stage, if a particular handler is to be removed, you must have a reference to it which can be passed to removeEventListener (Mozilla, Netscape, Firefox) or detachEvent (IE).

An elaborate explanation on this topic can be found at http://www.howtocreate.co.uk/tutorials/javascript/domevents.

Advertisement

About this entry