Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Namespaced Custom Events Trigger

Tags:

jquery

I'm stumped on how namespaced custom events are supposed to work in jQuery. I got the impression from the doc that triggering a namespaced custom event will only fire handlers specifically bound to that event. Instead, it seems the namespace is pretty much ignored. Example below and live code here: http://jsfiddle.net/kZCBw/1/

    $(document)
        .bind("reset.one", function(){ console.log("reset.one event detected");})
        .bind("reset.two", function(){ console.log("reset.two event detected");})
        .bind("cheese", function(){ console.log("cheese event detected");});

        $("#btn1").click(function(){
            console.log("firing reset.one event");
            $(this).trigger("reset.one");
        });
        $("#btn2").click(function(){
            console.log("firing reset.two event");
            $(this).trigger("reset.two");
        });
        $("#btn3").click(function(){
            console.log("firing reset event");
            $(this).trigger("reset");
        });

        //btn1 click should only trigger handlers bound to "reset.one"
        //and yet it triggers anything starting w/ "reset"

What am I missing?

Thanks in advance! -matt

like image 945
busticated Avatar asked Jan 17 '11 23:01

busticated


1 Answers

I can at least corroborate your example an add an observation.

If you make the button the listener (see http://jsfiddle.net/kZCBw/2/), better reflecting the sample code in the documentation, it works as expected.

But if you move it anywhere higher up in the DOM tree (see http://jsfiddle.net/kZCBw/3/), it fails.

At first, I suspected that this was because the namespace wasn't being bubbled up with the event object, but I appended the following code (live example at http://jsfiddle.net/kZCBw/4/):

$('*').bind('reset', function(e){
    console.log(e.type + '.' + e.namespace + ' detected at ' + e.currentTarget);
});

As you can see, the namespace is being bubbled up just fine.

While the behaviour you're looking for (namespace remaining effective at higher level DOM nodes) is not explicitly exemplified in the documentation, I feel that it should be the way namespaced events work. To this extent, you can now begin the "bug or feature" hunt.

A makeshift way to accomplish what you're looking for without touching the jQuery source code is to just filter the event using the EventObject (I suspect this is how namespaced events are accomplished in jQuery in the first place) inside the event handler.

like image 143
Steven Avatar answered Sep 24 '22 12:09

Steven