Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - how to check if event already added

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.

like image 488
Shlomo Avatar asked Jul 11 '12 10:07

Shlomo


People also ask

How do I know if an event listener is added?

To check if an element has event listener on it with JavaScript, we can call the getEventListeners function in the Chrome developer console. getEventListeners(document. querySelector("your-element-selector")); in the Chrome developer console to select the element we want to check with querySelector .

How do you check if an element has an event listener JS?

Right-click on the search icon button and choose “inspect” to open the Chrome developer tools. Once the dev tools are open, switch to the “Event Listeners” tab and you will see all the event listeners bound to the element. You can expand any event listener by clicking the right-pointing arrowhead.

How do I get rid of addEventListener?

Event listeners can also be removed by passing an AbortSignal to an addEventListener() and then later calling abort() on the controller owning the signal.


1 Answers

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

like image 192
user4584026 Avatar answered Sep 24 '22 16:09

user4584026