dispatchEvent是同步还是异步功能 [英] Is dispatchEvent a sync or an async function

查看:703
本文介绍了dispatchEvent是同步还是异步功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为WinJS中的自定义事件编写事件处理程序。我不太确定它在IE中是如何工作的 -
我正在创建一个自定义事件并调度它 -

I am trying to write an event handler for a custom event in WinJS. I am not too sure how this works in IE - I am creating a custom event and dispatching it -

var eventObject = document.createEvent("CustomEvent");
eventObject.initCustomEvent("dropbomb", true, true, null);
this._element.dispatchEvent(eventObject);

我的处理程序是 -

My handler is -

this._element.addEventListener("logtelemetry", function () {
                console.log("boom");
});

我可以确定将同步调用处理程序而不是以后调用吗?如果是,那么什么是证明。

Can I be certain that the handler will be called in sync and not at a later time? If so then what is the proof.

推荐答案

它保证是同步的,因为:

It’s guaranteed to be synchronous because:


dispatchEvent的返回值指示是否有任何处理该事件的
侦听器名为preventDefault。

The return value of dispatchEvent indicates whether any of the listeners which handled the event called preventDefault.

由于返回值指示是否有任何处理该事件的侦听器调用了preventDefault,因此该方法必须阻塞(不返回),直到所有侦听器都执行完为止,这是同步调用的定义。

Since the return value indicates whether any of the listeners that handled the event called preventDefault, the method must block (not return) until all of the listeners are done executing, which is the definition of a synchronous call.

上述引文摘自 DOM Level 2 Events中的dispatchEvent规范,在2000年11月达到了推荐状态(标准).Internet Explorer符合此标准因为至少IE 9

The above quotation is an excerpt from the dispatchEvent specification in DOM Level 2 Events, which achieved "Recommendation" status (a standard) back in November 2000. Internet Explorer has complied with this standard since at least IE 9.

要自己验证,请添加 console.log 紧跟在 .dispatchEvent 之后的声明并注意到boom(来自你的事件处理程序) )总是先记录下来。

To verify for yourself, add a console.log statement immediately after your .dispatchEvent call and notice that "boom" (from your event handler) is always logged first.

这篇关于dispatchEvent是同步还是异步功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆