(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?
Yes. JavaScript is not multithreaded. When you trigger events, all event handlers are immediately executed.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With