jquery event namespace bubbling issue

Posted by Adrian Adkison on Stack Overflow See other posts from Stack Overflow or by Adrian Adkison
Published on 2010-04-29T22:03:46Z Indexed on 2010/04/29 22:07 UTC
Read the original article Hit count: 253

Filed under:
|

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

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about JavaScript