Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ensure jQuery event handler execution order

I think that event handlers are processed in the order that they are registered. (Is that correct?) If that is the case then if I attach an event handler at the beginning of my script, can I be absolutely certain that it will fire before subsequent handlers attached to the same event? Also do event namespaces have any effect on this? Are event handlers fired in series (one finishes before the next) or in parallel?

I want to do this because my script relies on the viewport size, which changes on the resize event, and I need to constantly look for it. Rather than calling $(window).width() repeatedly in each of my handler functions, I'd like to put a handler at the top of my script that saves $(window).width() to an object property on each resize. Then in subsequent handlers I can access the property and be certain that it is the most recent measurement.

I know I could create a custom event that triggers as soon as the calculation is done and attach subsequent handlers to the custom event. But, I'd don't want to do that because I need to maintain interoperability with plugins that come after mine that may also be attaching to the resize event.

like image 516
ryanve Avatar asked Jan 27 '12 16:01

ryanve


1 Answers

If you attach your event handler before any other script has run (even just a plugin), then your callback will always fire first.

You can inspect the array of event handlers through the data object:

$(window).data('events');

Note: this is a non-documented approach and might not work eventually. Use it for inspection only.

like image 162
Joseph Silber Avatar answered Oct 08 '22 23:10

Joseph Silber