Make sure jQuery event handler execution order

I think event handlers are processed in the order in which they are registered. (Is this correct?) If so, then if I attach an event handler at the beginning of my script, can I be absolutely sure that it will fire before subsequent handlers attached to the same event? Do event namespaces also affect this? Event handlers run sequentially (one ends before the next) or in parallel?

I want to do this because my script relies on the viewport size, which changes to the resize event, and I need to constantly look for it. Instead of repeatedly calling $(window).width() in each of my handler functions, I would like to place a handler at the top of my script, which saves the $(window).width() property of the object every time it resizes. Then in subsequent handlers, I can access the property and be sure that this is the last dimension.

I know that I can create a custom event that fires as soon as the calculation is done, and attaches subsequent handlers to the custom event. But I would not want to do this, because I need to maintain compatibility with plugins that appear after mine, which can also be associated with a resize event.

+6
source share
1 answer

If you attach an event handler before running any other script (even a plugin), then your callback will always be run first.

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

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

Note: this is not a documented approach and may not work in the long run. Use it only for inspection.

+4
source

Source: https://habr.com/ru/post/907053/


All Articles