AIFeed

addEventListener discards duplicates

Original text(via Lobsters)

A little-known quirk of the addEventListener method in the HTML DOM is that it discards duplicates.


        let counter = 0;
function logMessage(e) {
    console.log(`${++counter} ${e.detail.text}`);
}

let sampleEvent = new EventTarget();

sampleEvent.addEventListener("message", logMessage);
sampleEvent.addEventListener("message", logMessage);

// This prints only one message!
sampleEvent.dispatchEvent(new CustomEvent("message",
    { detail: { text: "hello" } } ));

// This removes the (singular) event handler.
sampleEvent.removeEventListener("message", logMessage);

// No message!
sampleEvent.dispatchEvent(new CustomEvent("message",
    { detail: { text: "anybody there?" } } ));
      

This behavior is part of the specification:

If eventTarget’s event listener list does not contain an event listener whose type is listener‘s type, callback is listener‘s callback, and capture is listener‘s capture, then append listener to eventTarget‘s event listener list.

The new listener is added only if it doesn’t already exist on the target with the same type (event name), callback, and capture mode.

But what if you really want to be notified twice?

You will want to register two different function objects that both lead to the same underlying function. For example, you could wrap them inside separate functions.


        let handler1 = function(e) { logMessage(e); };
let handler2 = function(e) { logMessage(e); };
sampleEvent.addEventListener("message", handler1);
sampleEvent.addEventListener("message", handler2);

⟦ ...

sampleEvent.removeEventListener("message", handler1);
sampleEvent.removeEventListener("message", handler2);
      

Or you could use a lambda.


        let handler1 = e => logMessage(e);
let handler2 = e => logMessage(e);
      

Or you could use bind().


        let handler1 = logMessage.bind();
let handler2 = logMessage.bind();
      

Normally, bind() is used to bind to the current this. Here, we bind to nothing since logMessage doesn’t use this anyway. Each bind produces a new function object, so they are considered distinct callbacks for the purpose of addEventListener duplicate removal.

Note that in all cases, if you want to remove the handler later, you need to remember it so that you can pass it to removeEventListener.

The text above was extracted automatically from the source page and may miss images, tables or code blocks. The original is authoritative.

Published by Lobsters
This site only summarises and aggregates; copyright stays with the original author. Headlines and summaries follow the source — where they differ, the original wins.
Read the original ↗