How to add multiple event listeners

Hi everyone,

i am trying to use addEventListener for adding multiple on change listeners to one select object.

cell.addEventListener("change", function () { /* .... */ });

Is there a right way to do it with select2? “onchange” will not work for us because this will overwrite the existing listener, if i’m not mistaken.

Thanks for the help!

Select2 doesn’t impose any unique requirements on adding event listeners (nor provide any custom features for managing event listeners). You can certainly call addEventListener() multiple times on the same element, even for the same event type. Each event listener will be executed in the order it is added (unless you set the “capture” option to true, or call stopImmediatePropagation() in one of the handlers (which would prevent any further handlers from receiving that event).

However, instead of adding multiple separate handlers or the “change” event, could you create a single event handler function that performs all the logic that your separate handlers would have performed? (Note that those separate bits of logic could—and probably should—be encapsulated in separate functions. The “change” handler function would then just call those individual logic functions in whatever order is needed by your application.)

I could see adding multiple event handlers if you need to add (and possibly remove) them dynamically, but even that could be done with a single event handler and individual logic functions.

In any case, you’re doing it right. The Mozilla Developer Network (MDN) site has excellent documentation about addEventListener().

1 Like

Thanks John!
So we must do something wrong when applying addEventListener, we’ll look into it.