jquery event namespace bubbling issue
- by Adrian Adkison
Hi,
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>
Here is the jQuery
jQuery('#content div.child')
.bind('child.a',function(){alert('a-child');})
.bind('child.b',function(){alert('b-child');})
.bind('child.c',function(){alert('c-child');});
jQuery('#content div.parent')
.bind('child.b',function(){alert('b-parent');})
.bind('child.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