简体   繁体   English

dispatchEvent 如何同步执行 addEventListener 的处理程序?

[英]How does dispatchEvent execute addEventListener's handler synchronously?

 let section = document.querySelector('section'); function handler(e) { console.log(e.detail.color); } section.addEventListener('hello', handler); let event = new CustomEvent("hello", {detail: {color: "red"}}); if (section.dispatchEvent(event)) { console.log("true") } else { console.log("false"); }
 <section></section>

In this example, I'm struggling to understand how handler is executed during the initial execution of the file - leading us to log red before true .在这个例子中,我正在努力理解在文件的初始执行期间handler是如何执行的 - 导致我们在true之前记录red I thought that handlers waited for the event somewhere, and when the event happened, they were put in the macro-task queue which means they'd only be put on the call-stack after the initial execution of the file.我认为处理程序在某处等待事件,当事件发生时,它们被放入宏任务队列,这意味着它们只会在文件初始执行后放入调用堆栈。

Am I safe to assume that dispatchEvent has a unique way of executing .addEventListener 's handler synchronously?我可以安全地假设dispatchEvent有一种独特的方式来同步执行.addEventListener的处理程序吗?

Or do I have a misunderstanding of the way the handler in .addEventListener executes?还是我对.addEventListener处理程序的执行方式有误解? I thought it executed asynchronously.我认为它是异步执行的。

I thought that handlers waited for the event somewhere我以为处理程序在某处等待事件

They do - but you just happened to fire the event immediately, so the handler is run immediately.他们这样做 - 但你碰巧立即触发事件,所以处理程序立即运行。

and when the event happened, they were put in the macro-task queue which means they'd only be put on the call-stack after the initial execution of the file.当事件发生时,它们被放入宏任务队列,这意味着它们只会在文件初始执行后被放入调用堆栈。

I don't know what "initial execution of the file" means.我不知道“文件的初始执行”是什么意思。 Handlers are run whenever an event is dispatched.每当调度事件时都会运行处理程序。

Am I safe to assume that dispatchEvent has a unique way of executing .addEventListener's handler synchronously我可以安全地假设 dispatchEvent 有一种独特的方式来同步执行 .addEventListener 的处理程序

No, nothing strange is happening here, this is all normal stuff.不,这里没有发生任何奇怪的事情,这都是正常的事情。

Or do I have a misunderstanding of the way the handler in .addEventListener executes?还是我对 .addEventListener 中处理程序的执行方式有误解? I thought it executed asynchronously.我认为它是异步执行的。

Handlers get executed synchronously.处理程序同步执行。 Whenever an event is dispatched, handlers are checked and any matching ones are executed synchronously in the order they have been added.每当调度事件时,都会检查处理程序,并按照添加顺序同步执行任何匹配的处理程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM