事件监听器


🌐 Event listener

注册到某个事件 type 的事件监听器可以是 JavaScript 函数,也可以是拥有 handleEvent 属性(其值为函数)的对象。

🌐 Event listeners registered for an event type may either be JavaScript functions or objects with a handleEvent property whose value is a function.

在任何情况下,处理函数都会被调用,并传入传递给 eventTarget.dispatchEvent() 函数的 event 参数。

🌐 In either case, the handler function is invoked with the event argument passed to the eventTarget.dispatchEvent() function.

异步函数可以用作事件监听器。如果异步处理函数被拒绝,该拒绝将被捕获并按照 EventTarget 错误处理 所述进行处理。

🌐 Async functions may be used as event listeners. If an async handler function rejects, the rejection is captured and handled as described in EventTarget error handling.

一个处理函数抛出的错误不会阻止其他处理函数被调用。

🌐 An error thrown by one handler function does not prevent the other handlers from being invoked.

句柄函数的返回值会被忽略。

🌐 The return value of a handler function is ignored.

句柄始终按照其添加的顺序被调用。

🌐 Handlers are always invoked in the order they were added.

处理函数可能会修改 event 对象。

🌐 Handler functions may mutate the event object.

function handler1(event) {
  console.log(event.type);  // Prints 'foo'
  event.a = 1;
}

async function handler2(event) {
  console.log(event.type);  // Prints 'foo'
  console.log(event.a);  // Prints 1
}

const handler3 = {
  handleEvent(event) {
    console.log(event.type);  // Prints 'foo'
  }
};

const handler4 = {
  async handleEvent(event) {
    console.log(event.type);  // Prints 'foo'
  }
};

const target = new EventTarget();

target.addEventListener('foo', handler1);
target.addEventListener('foo', handler2);
target.addEventListener('foo', handler3);
target.addEventListener('foo', handler4, { once: true });