最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Do Javascript event handlers block? - Stack Overflow

programmeradmin1浏览0评论

(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?

(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?

Share Improve this question asked Mar 28, 2012 at 0:34 gxcgxc 5,1186 gold badges41 silver badges56 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

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.

发布评论

评论列表(0)

  1. 暂无评论