LA.NET [EN]

Aug 05

JQuery: more on the triggerHandler method

Posted in JQuery      Comments Off on JQuery: more on the triggerHandler method

In the previous post I’ve shown you some code on how to use the triggerHandler method. At the time, I said that events would bubble even though the docs say that they won’t. I based my conclusions on a small simple test I’ve written. ingmar added more information on a comment saying that if you have a more complex tree, you won’t get the “correct” bubbling. For instance, with the following structure:

<div>
    <p>This is some hidden content</p>
    <p>And more hidden content</p>
</div>

you’ll get the following bubbling: P->BODY->HTML. So, what’s happening here? Well, it’s simple: I was wrong. The fact is that the bubbling I was seeing was coming from my button’s click event and not from the triggered element. Let’s take another peek at the script code I’ve written:

<script type="text/javascript">
    $(function() {
        $("*").not("input").click(function(evt) {
            alert(evt.currentTarget.tagName + " clicked");
            return "hi";
        });
        $("#trigger").click(function() {
            $("p").trigger("click");
        });
        $("#triggerHandler").click(function() {
            alert($("p").triggerHandler("click"));
        });
    });
</script>

As you can see, we’re hooking up all the elements’ click event (excluding inputs) with an anonymous function that displays an alert message with the tagName of the current target element. Now, when I wrote the small sample, I concentrated on the P’s click event and this was what I saw:

P->BODY->HTML

Since my initial markup looked like this:

<p>This is some hidden content</p>
<p>And more hidden content</p>

I completely forgot that the click event of the button would also propagate through the tree until it reaches the top element. Notice that when you dispatch an event from within an existing handler, that handler will be “suspended” until that “new” event is completely dispatched. When that happens, the “previous” event that was in “stand by” wakes up and goes through its normal lifecycle. So, if I had written this code:

$("#triggerHandler").click(function(evt) {
    alert($("p").triggerHandler("click"));
    evt.stopPropagation();
});

it would have been obvious that there was no bubbling coming from the P’s click event that has been dispatched through that anonymous function. I guess that the moral of the story is that I should pay more attention to the samples I’m writing during my JQuery tests. Thanks go to ingmar for putting me in the right track. Keep tuned for more on JQuery.