JavaScript - how to check if event already added

前端 未结 3 1903
耶瑟儿~
耶瑟儿~ 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.

提交回复
热议问题