JavaScript - how to check if event already added

Shlomo picture Shlomo · Jul 11, 2012 · Viewed 42.4k times · Source

I want to add an listener exactly once for beforeunload. This is my pseudocode:

if(window.hasEventListener('beforeunload') === false) {
     window.addEventListener('beforeunload', function() { ... }, false);
}

But hasEventListener does not exist obviously. How can I achieve this? Thanks.

Answer

user4584026 picture user4584026 · Feb 19, 2015

In fact there is no need to check if an listener was added to a target:

If multiple identical EventListeners are registered on the same EventTarget with the same parameters, the duplicate instances are discarded. They do not cause the EventListener to be called twice, and since the duplicates are discarded, they do not need to be removed manually with the removeEventListener method.

Source:https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener#Multiple_identical_event_listeners