事件监听器


为事件 type 注册的事件监听器可以是 JavaScript 函数,也可以是具有值为函数的 handleEvent 属性的对象。

在任何一种情况下,句柄函数都是通过传给 eventTarget.dispatchEvent() 函数的 event 参数调用的。

异步函数可用作事件监听器。 如果异步的句柄函数拒绝,则会按照 EventTarget 错误处理中的描述捕获和处理拒绝。

句柄函数抛出的错误不会阻止其他句柄被调用。

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

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

句柄函数可能会改变 event 对象。

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

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

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

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

const target = new EventTarget();

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

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

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

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.

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 });