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
189 views
in Technique[技术] by (71.8m points)

javascript - One listener for ALL events in jQuery event namespace?

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 a certain namespace?

Such as:

$(window).on(".event_namespace", function(e){
    //handler
});

$(window).trigger("testEvent.event_namespace");
$(window).trigger("testEventTwo.event_namespace");

With the intended behavior being that the listener would capture any event triggered with the specified namespace...

The end-goal is simply to be able to listen to a group of events that will actually be fired by code that I don't have access too. I'd like to be able to say, "just add your event to this namespace," and then be able to capture those without needing to know the event names themselves; only the namespace.

Possible?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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/


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

...