JavaScript - 如何检查事件是否已添加 [英] JavaScript - how to check if event already added

查看:107
本文介绍了JavaScript - 如何检查事件是否已添加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为 beforeunload 添加一个监听器。这是我的伪代码:

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

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

hasEventListener 显然不存在。我怎样才能做到这一点?谢谢。

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

推荐答案

使用jquery你可以使用数据(events)在任何对象上(这里是窗口):

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

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

但这仅适用于jquery添加的事件。

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);
   }

我认为javascript中没有标准的方式来获取现有的事件处理程序。最好你可以附加Node的addEventListener函数来拦截和存储监听器,但我不推荐它...

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...

编辑:

从jQuery 1.8开始,事件数据在 $ ._ data(element,events)中可用。更改日志有一个警告应该考虑在内:

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.

这篇关于JavaScript - 如何检查事件是否已添加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆