jquery event namespace bubbling issue
I stumbled upon an issue with event namespacing while developing a jQuery plugin.
here is the html
<div class="parent">
<div class="child">
</div>
</div>
<a class="btn-a">trigger a</a>
<a class="btn-b">trigger b</a>
<a class="btn-c">trigger c</a&g开发者_如何学运维t;
Here is the jQuery
jQuery('#content div.child')
.bind('a.a',function(){alert('a-child');})
.bind('a.b',function(){alert('b-child');})
.bind('a.c',function(){alert('c-child');});
jQuery('#content div.parent')
.bind('a.b',function(){alert('b-parent');})
.bind('a.c',function(){alert('c-parent');});
jQuery('a.btn-a')
.click(function(){
jQuery('#content div.child').trigger('a.a');
});
jQuery('a.btn-b')
.click(function(){
jQuery('#content div.child').trigger('a.b');
});
jQuery('a.btn-c')
.click(function(){
jQuery('#content div.child').trigger('a.c');
});
In sum, I have attached a namespaced event listener to the child and parent and created three buttons that trigger each of the events(a.a, a.b, a.c). Note the parent is only listening to a.b and a.c. When I click on the button that triggers a.a on the child, only the div.child listener for a.a is fired, but the entire 'a' namespace event bubbles up to div.parent listeners, a.b and a.c, and triggers them. My question is, how would I still use event namespacing but only have the intended event bubble up(i.e. a.a is the only event that fires for both child and parent). I am aware of stopPropagation and stopImmediatePropagation. I would not want to put these on the child a.b and a.c listeners because there are times when i do want them to bubble. For instance when I trigger 'a.b' on the child, I would expect the 'a.b' and only the 'a.b' event to be handled by the child and the parent.
Thanks
I'm not entirely sure from the question, but it seems like this is the behavior you want: http://jsfiddle.net/cHrSG/
Namespaces are after the event, not before, so the format is event.namespace
, the jQuery docs have a thorough read here. If you swap them around your code has the expected effect, at least I think it's what you expect best as I can tell from the question:
jQuery('#content div.child')
.bind('a.a',function(){alert('a-child');})
.bind('b.a',function(){alert('b-child');})
.bind('c.a',function(){alert('c-child');});
jQuery('#content div.parent')
.bind('b.a',function(){alert('b-parent');})
.bind('c.a',function(){alert('c-parent');});
jQuery('a.btn-a')
.click(function(){
jQuery('#content div.child').trigger('a.a');
});
jQuery('a.btn-b')
.click(function(){
jQuery('#content div.child').trigger('b.a');
});
jQuery('a.btn-c')
.click(function(){
jQuery('#content div.child').trigger('c.a');
});
精彩评论