如何绑定到jQuery中的所有自定义事件 [英] How to bind to all custom events in jQuery

查看:218
本文介绍了如何绑定到jQuery中的所有自定义事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道不可能绑定到所有DOM事件,我知道你可以通过提供以空格分隔的列表来绑定多个事件。

I know it's not possible to bind to all DOM events and I know you can bind to multiple events by supplying a space-separated list.

但它是否可能绑定到所有自定义事件(最好通过'abc *'或名称空间等通配符模式过滤)?

But is it possible to bind to all custom events (preferably filtered by a wildcard pattern like 'abc*' or name-space)?

编辑:
为了澄清,我创建了一些响应某些自定义事件的自定义小部件。例如,他们都处理一个名为'stepReset'的事件并重置他们的内部模型。

To clarify, I have created some custom widgets that respond to some custom events. For example, they all handle an event called 'stepReset' and resets their internal models.

在我写完之后,我意识到事件不会消失,所以调用 $(body).trigger('stepReset')基本上什么都不做。因此,我正在考虑在所有小部件的父元素上添加一个伞形事件处理程序,以传播所有相关事件。

After I've written these, I realized events don't bubble down, so the call $(body).trigger('stepReset') basically does nothing. As a result, I am considering adding an umbrella event handler on all widgets' parent elements to propagate all relevant events down.

(我知道这不是一个优雅的解决方案,但是我忘了用带有公共类的处理程序标记元素,所以没有简单的方法可以使用它们全部选择。)

(I know this is not an elegant solution, but I forgot to tag elements with handlers with a common class, so there's no easy way to use select them all.)

推荐答案

关于即将进行的编辑,您可以通过访问对象的数据来检索所有绑定事件:

With regards to your upcoming edit, you can retrieve all bound events by accessing the object's data:

var boundEvents = $.data(document, 'events');

从此处,您可以迭代生成的对象并检查所选通配符的每个属性,或者迭代该属性的数组元素并检查每个元素的 namespace 属性。

From here, you can iterate over the resulting object and check each property for your chosen wildcard character, or iterate over that property's array elements and check the namespace property of each.

例如,

$.each(boundEvents, function () {
    if (this.indexOf("*"))   // Checks each event name for an asterisk *
        alert(this);

    // alerts the namespace of the first handler bound to this event name
    alert(this[0].namespace); 
});






如果我理解正确, 您可以迭代特殊事件对象以获取自定义事件列表(包括在jQuery源代码中指定的事件)。这是一个ES5示例,您需要自己为旧浏览器进行调整,或者使用填充以获取 Object.keys


If I understood you correctly, you can iterate over the special events object to get a list of custom events (including those specified in the jQuery source code). Here's an ES5 example, you will need to adapt it yourself for older browsers or use a polyfill for Object.keys:

var evts = Object.keys(jQuery.event.special).join(" ");
$("#myDiv").on(evts, function (e) {
    // your code here
});

这篇关于如何绑定到jQuery中的所有自定义事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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