views:

225

answers:

1

Overview of the problem

In jQuery, the order in which you bind a handler is the order in which they will be executed if you are binding to the same element.

For example:

$('#div1').bind('click',function(){
// code runs first
}); 

$('#div1').bind('click',function(){
// code runs second
});

But what if I want the 2nd bound code to run first?

.

My current solution

Currently, my solution is to modify the event queue:

$.data(domElement, 'events')['click'].unshift({
                            type : 'click',
                            guid : null,
                            namespace : "",
                            data : undefined,
                            handler: function() {
                                // code
                            }
                        });

.

Question

Is there anything potentially wrong with my solution?

Can I safely use null as a value for the guid?

Thanks in advance.

.

+1  A: 

There's an interesting plugin called eventstack. It lets you bind events to either the top or the bottom of the event queue. I don't know how general your problem is, or whether you're looking to reverse or to arbitrarily order events in your stack, but the plugin may simplify your task.

If you're looking to assemble your queue in a very specific order, you can try the approach suggested in this answer -- building custom events that can trigger each other in turn.

Your approach may be the best for your requirement, but perhaps these are options as well.

Ken Redler
Thanks. Since I'm writing a plugin, I don't want to require the user to manually trigger a custom event I made each time. I want to it be automatic.Eventstack does not help either because I do not want to reverse the stack, but simply place my plugin's event at the beginning of the stack.
resopollution