Exit handler being called multiple times

Everytime the exit button is clicked, the handler is being called multiple times.

To reproduce, clicking on the Exit button 1 time, after another, produces these numbers inside console.log. https://jsfiddle.net/xcq0L372/

Clicking on the exit button one time gives 1
a 2nd time gives, 3
3rd time: 6
4th time:10
5th time: 15

1, 3, 6, 10, 15

Those numbers instead should be.

1, 2, 3, 4, 5

How would that be fixed in the code?

 function createResetHandler(player) {
    const resetVideo = document.querySelectorAll(".exit");
    resetVideo.forEach(function resetVideoHandler(video) {
        video.addEventListener("click", function resetVideoHandler() {
            player.destroy();
            console.log("hit");
          }
        );
      }
    )
  }

In this example, clicking on 1 exit gave 1, a 2nd gave 3, and a 3rd exit gave 6.

Those numbers should be, 1, 2 , 3, not, 1, 3, 6.

In 99% of all cases adding an event handler in a loop is a very bad idea…

1 Like

I asked if that statement was true and was given this information:

No, consider the example where you create an element inside the loop, imagine this as a grid- you use a loop to add divs to it and attach an event listener to those div. The event handler is being attached inside the loop. And this is quite common in my experience.

Besides, objectively stating this as a fact is bad. I mean, attaching event handler inside a loop to a single element would be bad but you cannot still state it objectively. Consider the weird scenario where you have got array of events or event listener callback, if you iterate over the array and attach it to a single element it can make up for a good use case.

In response to that someone said this:

imagine this as a grid- you use a loop to add divs to it and attach an event listener to those div.

Why not just attach a single event listener to the root element of the grid and use event delegation?

The reason this is usually considered bad practice is it’s generally more efficient to attach a single event listener to a parent element and check the event’s target property. This is called “event delegation”. Here are some resources you can read about this technique:

https://davidwalsh.name/event-delegate

https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#event_delegation

I didn’t state it as a fact. I said only 99% :smiley: