views:

32

answers:

2

Example:

$(X).bind('click', function() { alert( 'Two' ); });
$(X).bind('click', function() { alert( 'Three' ); });
$(X).bind('click', function() { alert( 'Four' ); });
$(X).bind('click', function() { alert( 'Five' ); });

**$(X).bindUp('click', function() { alert( 'One' ); });**

When the user click X the output should be:

alert( 'One' );
alert( 'Two' );
alert( 'Three' );
alert( 'Four' );
alert( 'Five' );

It's possible??

Thanks......................

A: 

You can attach as many event handlers as you want (technically).

$(function(){
    $('div').click(function(){
        alert('one');
    }).click(function(){
        alert('two');
    }).click(function(){
        alert('three');
    });
});​


http://www.jsfiddle.net/YjC6y/12/
jAndy
I think you missed the question, he wants to bind them out of order.
Nick Craver
+2  A: 

For simple cases, I think you could do something like this:

Example: http://jsfiddle.net/uEEzt/2/

$.fn.bindUp = function(type, fn) {

    this.each(function() {
        $(this).bind(type, fn);

        var evt = $.data(this, 'events')[type];
        evt.splice(0, 0, evt.pop());
    });
};

When you use this .bindUp() plugin, it just does a normal .bind(), but then removes the event from the end, and places it at the beginning.

Again, this would be for simple cases only.


EDIT: It should be simple to make this work with multiple events, but don't try to use it with hover.


EDIT: Here's a version that works with multiple (space separated) events (again, don't use with hover):

Example: http://jsfiddle.net/uEEzt/4/

$.fn.bindUp = function(type, fn) {

    type = type.split(/\s+/);

    this.each(function() {
        var len = type.length;
        while( len-- ) {
            $(this).bind(type[len], fn);

            var evt = $.data(this, 'events')[type[len]];
            evt.splice(0, 0, evt.pop());
        }
    });
};

EDIT: Fixed mistake in "multiple" version where len variable was not reset.

patrick dw
Thanks! this is the correct answer!
Cris Hong Kong CRISHK