I read an article (link) which explains that the seconde argument of addEventListener can be a function or an object implementing handleEvent method.

In the But wait there’s more section of this article, it says using handleEvent can avoid removing and re-attach the event handler. But I'm wondering if this is a better way than repeatedly 'add' and 'remove'? In terms of tidy code, performance or whatever?

Thank you all!

1

There are 1 best solutions below

0
On

Using an object as a listener:

var listener = 
    {
    handleEvent: function (evt) {
 
        this === listener; // true
 
        // and evt === classic event object
    }
};


document.addEventListener("click", listener, false);

has the following advantages:

  • It separates the interface from the implementation
  • It helps avoid circular references to DOM objects
  • It isolates this from the Event object

Specification authors should not define callback interfaces that have only a single operation, unless required to describe the requirements of existing APIs. Instead, a callback function should be used.

The definition of EventListener as a callback interface is an example of an existing API that needs to allow user objects with a given property (in this case “handleEvent”) to be considered to implement the interface. For new APIs, and those for which there are no compatibility concerns, using a callback function will allow only a Function object (in the ECMAScript language binding).

References