简体   繁体   中英

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

Or do I have a misunderstanding of the way the handler in .addEventListener executes? 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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