views:

1087

answers:

1

I am trying to prevent JavaScript events from continuing to propagate, using YUI. The following is some minimal HTML and some minimal JavaScript which demonstrates the problem:

HTML:

<a href="#foo" onClick="fooClickTest()" id="foo">foo</a>&nbsp;
<a href="#bar" id="bar">bar</a>&nbsp;

JavaScript:

function fooClickTest(e) {
    alert('fooClickTest');
    YAHOO.util.Event.addListener('bar', 'click', barClickTest1);
    YAHOO.util.Event.addListener('bar', 'click', barClickTest2);
    YAHOO.util.Event.addListener('bar', 'click', barClickTest3);
    YAHOO.util.Event.preventDefault(e);
}

function barClickTest1(e) {
    alert('barClickTest1');
    YAHOO.util.Event.preventDefault(e);
}

function barClickTest2(e) {
    alert('barClickTest2');
    YAHOO.util.Event.preventDefault(e);
    YAHOO.util.Event.stopEvent(e);
// Also tried:
//  YAHOO.util.Event.stopPropagation(e);
// and:
//        if (e.stopPropagation) {
//            e.stopPropagation();
//        } else {
//            e.cancelBubble = true;
//        }
}

What I expect to happen is that the user can click on 'foo' to add the three click handlers, and then click on 'bar'. Then, the user will see TWO alerts, 'barClickTest1' and 'barClickTest2'. Instead, all three alerts occur. The YAHOO.util.Event.stopEvent(e) does not do what I expect, which is to stop the event propagating out to barClickTest3.

I have tested my code in Firefox 3.0.7 and in Safari 3.2.1. As you can see above, I have also tried YAHOO.util.Event.stopPropagation(e) and e.stopPropagation(). None of them did the trick.

This is obviously a contrived example, though it does demonstrate the problem. In the real solution, I will only prevent event propagation if some conditions are met.

Is my understanding of JavaScript's events simply messed up? How do I accomplish my goals?

+3  A: 

This isn't working as you expected because:

Without writing extra code there is no way to prevent certain event listeners on a single element from firing, and even if you could you couldn't be guaranteed the order the event listeners would be fired in.

You'll need to rewrite your code as a single event handler in order to be able to control if the code associated with your third click handler will execute.

Simon Lieschke
Thank you. You clearly explained why my expectations were mistaken. Sucks, but what can you do? By the way, I can guarantee the order the event listeners are fired in, our framework handles that, possibly for limited definitions of 'guarantee'.
ChrisInEdmonton