JavaScript - how to check if event already added

前端 未结 3 1901
耶瑟儿~
耶瑟儿~ 2020-12-14 06:56

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

if(window.hasEventListener(\'beforeunload\') === false) {
     w         


        
相关标签:
3条回答
  • 2020-12-14 07:38

    Using jquery you can do use data("events") on any object (here the window) :

    var hasbeforeunload = $(window).data("events") && $(window).data("events").['beforeunload'];
    

    But this works only for jquery added events.

    In a more general case, you should simply store the information that you add a listener somewhere :

       var addedListeners = {};
       function addWindowListenerIfNone(eventType, fun) {
          if (addedListeners[eventType]) return;
          addedListeners[eventType] = fun;
          window.addEventListener(eventType, fun);
       }
    

    I think there is no standard way in javascript to get the existing event handlers. At best you could surcharge the addEventListener function of Node to intercept and store the listeners but I don't recommend it...

    EDIT :

    From jQuery 1.8, event data are available in $._data(element, "events"). The change log has a warning that should be taken into account :

    Note that this is not a supported public interface; the actual data structures may change incompatibly from version to version.

    0 讨论(0)
  • 2020-12-14 07:46

    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

    0 讨论(0)
  • 2020-12-14 07:48

    In Chrome Dev tool, you can check all events attached to an element (For debugging)-

    // print all events attached to document
    var eventObjectAttachedToDocument = getEventListeners(document);
    
    for (var event in eventObjectAttachedToDocument) {
        console.log(event);
    }
    

    0 讨论(0)
提交回复
热议问题