How to order events bound with jQuery

后端 未结 12 1194
闹比i
闹比i 2020-11-22 13:09

Lets say I have a web app which has a page that may contain 4 script blocks - the script I write may be found in one of those blocks, but I do not know which one, that is ha

12条回答
  •  执笔经年
    2020-11-22 13:44

    Dowski's method is good if all of your callbacks are always going to be present and you are happy with them being dependant on each other.

    If you want the callbacks to be independent of each other, though, you could be to take advantage of bubbling and attach subsequent events as delegates to parent elements. The handlers on a parent elements will be triggered after the handlers on the element, continuing right up to the document. This is quite good as you can use event.stopPropagation(), event.preventDefault(), etc to skip handlers and cancel or un-cancel the action.

    $( '#mybutton' ).click( function(e) { 
        // Do stuff first
    } );
    
    $( '#mybutton' ).click( function(e) { 
        // Do other stuff first
    } );
    
    $( document ).delegate( '#mybutton', 'click', function(e) {
        // Do stuff last
    } );
    

    Or, if you don't like this, you could use Nick Leaches bindLast plugin to force an event to be bound last: https://github.com/nickyleach/jQuery.bindLast.

    Or, if you are using jQuery 1.5, you could also potentially do something clever with the new Deferred object.

提交回复
热议问题