动态添加javascript自定义事件并正确触发它们



我试图动态地使用自定义JavaScript事件,但它们似乎以我不希望的方式排队。示例代码:

<html>
<body>
<div id="app">
Testing
</div>
<script>
console.log("Sending event");
const event = new Event('testEvent', { cancelable: true });
document.body.querySelector('#app').dispatchEvent(event);
console.log("Event sent");
// now add an event handler
console.log("Adding listener");
document.body.querySelector('#app').addEventListener("testEvent", eventHandler());
// now send the event again
console.log("Sending event again");
document.body.querySelector('#app').dispatchEvent(event);
console.log("Event sent, done");
function eventHandler(evt) {
console.log("In eventHandler, got event");
};
</script>
</body>
</html>

在这里,我触发一个自定义事件,然后添加一个事件处理程序,然后再次触发自定义事件。至少在Chrome中,事件处理程序是由第一个触发器调用的,即使触发器发生在我添加事件处理程序之前。此外,即使在我再次触发事件之后,也不会再次调用事件处理程序。

我不希望第一个触发器导致调用事件处理程序。我确实希望第二个触发器能够调用它。我做错了什么?

您正在调用事件处理程序函数,并将返回值传递给addEventListener,这就是它立即且仅运行一次的原因。相反,您应该传递函数。

document.body.querySelector('#app').addEventListener("testEvent", eventHandler);
//not document.body.querySelector('#app').addEventListener("testEvent", eventHandler());

<html>
<body>
<div id="app">
Testing
</div>
<script>
console.log("Sending event");
const event = new Event('testEvent', { cancelable: true });
document.body.querySelector('#app').dispatchEvent(event);
console.log("Event sent");
// now add an event handler
console.log("Adding listener");
document.body.querySelector('#app').addEventListener("testEvent", eventHandler);
// now send the event again
console.log("Sending event again");
document.body.querySelector('#app').dispatchEvent(event);
console.log("Event sent, done");
function eventHandler(evt) {
console.log("In eventHandler, got event");
};
</script>
</body>
</html>

最新更新