How to bind to all custom events in jQuery

前端 未结 1 1696
旧时难觅i
旧时难觅i 2020-12-06 03:48

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

相关标签:
1条回答
  • 2020-12-06 04:00

    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
    });
    
    0 讨论(0)
提交回复
热议问题