简体   繁体   中英

Comparison between passing an object with a handleEvent property and traditional callback function in addEventListener

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM