Question

I bumped into some behavior which I did not expect. I'm not sure if this is a bug in jQuery or it simply works that way.
http://jsfiddle.net/7fRes/4/

Our application is generating quite a few event handlers which we want jQuery to call when we trigger them using a trigger on document (I think those are called 'global events'?). To have better control over what is happening we added namespaces to them.

$(document).on('evName.someThing', function(ev) {     
    output.append('<br />' + ++counter + ' triggered! ' + new Date().getSeconds()); 
})
output.on('evName2.funkyNameSpace', function() {
    output.append('<br />' + ++counter + ' funky click!');
})

It seems that triggering an event on document behaves different then triggering an event on a specific element:

  • events with namespaces on a specific element behave as we expected: the appropriate handlers are called when there's an exact match between event type and namespace:

example:

output.trigger('evName2');                // triggers (expected)
output.trigger('evName2.aaaaaNamespace'); // does not trigger (expected)
output.trigger('evName2.funkyNameSpace'); // triggers (expected)
  • but for global events, it seems adding namespaces does not allow us to restrict which handlers are called. It is as if it doesn't matter what namespace you add, the handers always get called. There only needs to be a matching event type.

example:

$.event.trigger('evName.someThingElse');    // triggers (hmmm?)
$.event.trigger('evName.someThinggg');     // triggers (hmmm?)
$.event.trigger('evName.foo');             // triggers (hmmm?)
$.event.trigger('evName');                 // triggers (expected)
$.event.trigger('evNameeeeee');            // does not trigger (expected)

Is this expected behavior? Or a bug?

Was it helpful?

Solution

It seems this is / was a bug in jQuery.

Upgrading our application to jQuery 1.10.x gives the behavior I was expecting.. See http://jsfiddle.net/7fRes/6/

(Heh.. SO forces me to put here some code before submitting my answer..)

$.event.trigger('evName.foo');             // does NOT trigger (expected!)
$.event.trigger('evName');                 // triggers (expected!)
$.event.trigger('evName.someThing');       // triggers (expected!)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top