Custom namespaced events will not work

 

Questions


I’m trying to get custom namespaced events to work as described here: http://docs.jquery.com/Namespaced_Events

But I must be missing something since I can’t get events to trigger unless the namespace matches exactly.

I created a fiddle to demonstrate the problem: http://jsfiddle.net/PsR6x/1/

What am I doing wrong?

Update

The second bind is invoked in jQuery v1.3.2 & v1.5.2 but not in v1.6.4 and above.
The third bind is not invoked in any version.

on instead of bind does not work either.

 

 

————————————————-

Answer

Event namespaces are not a hierarchy.
With the code that you have, $('#someid').trigger('griffin.model'); triggers all, and $('#someid').trigger('griffin.updated'); triggers all.

$('body').bind('griffin.model.updated.user', function() {
    alert('Exact namespace = trigger');
});
$('body').bind('griffin.model.updated', function() {
    alert('Will not trigger :(');
});
$('#someid').bind('griffin.model.updated', function() {
    alert('Same item, but not the same namespace = wont trigger');
});

Here you have essentially created three separate namespaces for the first, and two separate namespaces for the second and third.

Look carefully at this example and read the comments I left for you. It’s sometimes useful to try many different things, to see the different things you can do.

In regards to on() not working:
This snippet is taken directly from jquery-1.7.1.js:

bind: function( types, data, fn ) {
    return this.on( types, null, data, fn );
}

As you can see, bind() is simply a wrapper for on(), and should work exactly the same, with the exception of bind() not supporting selectors or delegation.

jquery

Facebook Comments

Post a comment