事件监听器
¥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 });