Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
127 views
in Technique[技术] by (71.8m points)

javascript - How to bind to all custom events in jQuery

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.

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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.

For instance,

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...