Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do Javascript event handlers block?

(Specifically, I'm using Backbone Model events)

Can someone help me understand how javascript events work? The following is not working the way I expected and it's left me confused:

In backbone, I make a change to my model, and immediately afterwards I run some code:

var myVar;
myModel.set('someAttr', true);  // Change my model
myVar = executeSomeFunc();  // Now run some code

Then somewhere else in my codebase I listen for the event and handle it (in my case I am wrapping this model with a collection):

myCollection.on('change:someAttr', changeHandler);  // Listen for the event

What I'm finding is that myVar = executeSomeFunc() is not executing until all the event handlers on the change:someAttr event are done firing. (I've checked by attaching a time consuming event handler onto the event)

Is this expected behavior?

like image 209
GxXc Avatar asked Sep 16 '26 01:09

GxXc


2 Answers

Yes. JavaScript is not multithreaded. When you trigger events, all event handlers are immediately executed.

like image 148
bhamlin Avatar answered Sep 17 '26 15:09

bhamlin


Everything in javascript blocks, it just depends when. If you set a handler the other functions, fire the event for the handler and run other functions it will get executed in the exact order i have enumerated them. The point of event-handlers is to execute code when triggering something, but it will never be asynchronous. So the answer for you is that YES this is the expected behavior. For understanding the heaven and the hell of javascript just search for Crockford's speeches about javascript.

Hope this helps.

like image 43
khael Avatar answered Sep 17 '26 15:09

khael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!