Tutorial :jQuery events chain - from stack to queue



Question:

Will execute in order 'first, second'. I need last as first executed.

function first(){ alert('first') }  function second(){ alert('second') }  $('input').click(first).click(second);  


Solution:1

Short answer: You can't do this.

Although in praxis browsers run events in the sequence that they were assigned you cannot trust that they will always do this. Also note that cancellations depend on which event model you use. In Level 1 (onclick="...") cancelling the event bubble takes effect immediately and no further handlers are run. This is not true for Level 2 (Element.addEventListener), which jQuery uses, where all handers registered on an element will always fire before propagation is stopped.

In my opinion, if you are writing something that depends on more than one handler function to run sequentially but don't have control of the sequence of assignments then you need to reconsider your approach.

However - if you must do this - you can unbind and reassign all events on the elements you need in order to get the desired sequence. You can get a list of events on a given element with $.data( someelement, 'events' ) and then un-/reassign them with your prefered event pushed to the front.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »