Skip to main content

handleEvent and addEventListener

Free2015-07-20#JS

Not written in books, but everyone uses it this way

I. What is handleEvent

addEventListener(strEventType, func, false/true);

This should be the most common way to add event handlers. Actually, the second parameter can also be an object with a handleEvent property, for example:

var obj = {
    // ...
    handleEvent: function() {
        // ...
        console.log('event fired');
    }
}
document.body.addEventListener('click', obj, false);

DOM Level 2 Events defines methods like add/removeEventListener, dispatchEvent, stopPropagation, preventDefault, initEvent, createEvent, etc. The second parameter type of add/removeEventListener is EventListener. In the EventListener interface definition, you can see it requires implementing the handleEvent method.

In other words, there are two ways to implement Eventlistener:

  • function objects implement the Eventlistener interface by default

  • Implement the handleEvent method on an object

For more information, please check DOM Level 3 event listener

II. Pros and Cons of Using handleEvent

1. this Binding

After adding an event handler with addEventListener('click', obj, false);, the this in the event handler function obj.handleEvent naturally points to obj.

After adding an event handler with addEventListener(strEventType, func, false/true);, the this in the event handler function func points to the host element of the event handler (simply put, the ele in ele.addEventListener). For example:

var ele = document.getElementById('test');
function handler(e) {
    console.log(this === ele);  // true
}
ele.addEventListener('click', handler, false);

The benefit of using addEventListener('click', obj, false); is that you can directly use the private properties of the obj object. Let's compare:

var obj = {
    // ...
    attr: 1,
    handleEvent: function() {
        // ...
        console.log(this.attr); // undefined, because after the event fires, this points to the host element body, and body doesn't have an attr property
    }
}
document.body.addEventListener('click', obj.handleEvent, false);

2. Dynamically Changing Event Handlers

You can dynamically change the event handler, for example: obj.handleEvent = obj.handler2; or obj.handleEvent = fun;. Very convenient, no need to remove first then add.

3. Disadvantages

The disadvantage is not about compatibility (DOM Level 2 Events is supported from IE9+, in other words, wherever you can use addEventListener, you can use obj.handleEvent), but about readability. I consider myself to have read quite a few JS books, but I have never seen this usage before. So, whether others can understand it when you write it is a problem.

References

Comments

No comments yet. Be the first to share your thoughts.

Leave a comment