Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery event handler queue

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.

.

like image 321
resopollution Avatar asked May 28 '10 21:05

resopollution


1 Answers

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.

like image 150
Ken Redler Avatar answered Sep 28 '22 00:09

Ken Redler