Trip
Trip

Reputation: 27114

Can you arrange the bubble order of event callbacks?

I have several objects listening for a change event, but I need them to fire off in a designated order.

Is it possible to customize the bubble order of several binded objects in jQuery?

Upvotes: 1

Views: 137

Answers (2)

adamb
adamb

Reputation: 4883

Unfortunately no, you cannot customize event bubble order.

To achieve the effect you desire, I would recommend jQuery custom events.

Example:

$("#YOURELEMENT").trigger('CUSTOMEVENT'); //create a new custom event
$("#YOURELEMENT2").bind('CUSTOMEVENT',function(e){ ... }); //listen for new custom event

Here's a good tutorial on it.

Upvotes: 1

Rikki
Rikki

Reputation: 3528

As far as I've experienced, there is an array of handlers which stores all the handlers referring the assigned functions. So when ever you add a new function for an event, it goes at the end of that array which means something like the code below:

$("SomeElement")
.live(
    {
        click: function ()
        {
            // This is handler named A.
            alert("A");
        }
    }
);

$("SomeElement")
.live(
    {
        click: function ()
        {
            // This is handler named B.
            alert("B");
        }
    }
);

B will be shown after A when "click" event triggered.

But when you change the places:

$("SomeElement")
.live(
    {
        click: function ()
        {
            // This is handler named B.
            alert("B");
        }
    }
);

$("SomeElement")
.live(
    {
        click: function ()
        {
            // This is handler named A.
            alert("A");
        }
    }
);

B will be shown before A when "click" event triggered.

You can order the adding handlers this way because the javascript code executes from in an up-down direction and I believe it's the only way.

Hope it helps.

Cheers

Upvotes: 1

Related Questions