One listener for ALL events in jQuery event namespace?

后端 未结 1 1355
灰色年华
灰色年华 2020-12-12 03:41

I know I have the ability to namespace events using jQuery\'s, $.fn.on, off and trigger functions. Is it possible to set up a handler that is able to listen to ALL events in

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

    Edit, Updated

    Try

        var ns = ".event_namespace", log = [];
    
        // place below block at bottom of script block , 
        // after `n` events attached to `n` window, document, elements 
    
        // listen for events having `ns` namespace ,
        // attached to `window, document, "*"` , above
        $(window, document, "*").on("event", function(e, ns, type) {
            // do stuff when event having `ns` occurs 
            log.push([ns, type]);
            $("#log").html("type, namespace: " + log.slice(-1)
                           + "<br> total <i>" + ns + "</i> events: " 
                           + log.length)
        });
    
        // if dynamic elements , events later attached ,
        // re-run this piece to add `event` event to those elements
        $.each([window, document, $("*")], function(k, v) {
            if($._data(v, "events") !== undefined) {
                $.each($._data(v, "events"), function(key, val) {
                    if (val[0].namespace === ns.slice(- (ns.length -1))) {
                        $(v).on(key + ns, function(e) {
                             $(e.target).trigger("event", [e.namespace, e.type])
                        })
                    }
                })
            }
        });
    

    jsfiddle http://jsfiddle.net/guest271314/s87j4o6r/4/

    0 讨论(0)
提交回复
热议问题