SMEETT
SMEETT

Reputation: 217

Multiple (identical) EventListeners on the same Element, why?

I tried to find an explanation but running out of things I can search for. I know this seems like a stupid question, but I am losing hope.

When I do the following, I get the behavior I would expect. I click button_2 and an eventListener is added to button_1.

const button_1 = document.getElementById("btn-1");
const button_2 = document.getElementById("btn-2");

const someFunction = () => {
    console.log("foo");
};

const addEvent = () => {
    button_1.addEventListener("click", someFunction);
};

button_2.addEventListener("click", addEvent);

However, when I try this and I click button_2 repeatedly, I end up with multiple eventListeners, all attached to button_1 which fire all at once when I click it. Why?

const button_1 = document.getElementById("btn-1");
const button_2 = document.getElementById("btn-2");

const addEvent = () => {
    const someFunction = () => {
        console.log("foo");
    };
    button_1.addEventListener("click", someFunction);
};

button_2.addEventListener("click", addEvent);

Any help much appreciated!

Upvotes: 3

Views: 765

Answers (1)

Quentin
Quentin

Reputation: 943635

In the first code example, someFunction is declared once and then applied as an event listener multiple times. Since each time it is applied it is the same function, it doesn't get added again.

In the second example, someFunction is declared inside the addEvent function; each time addEvent is called a new function is created and assigned to someFunction and then added as an event listener.

Since the functions are different (albeit identical), they are treated as separate functions and all added.

Upvotes: 5

Related Questions