eventTarget.addEventListener(type, listener[, options])


  • type <string>
  • listener <Function> | <EventListener>
  • options <Object>
    • once <boolean>true 时,监听器在首次调用时会自动被移除。默认值: false
    • passive <boolean>true 时,表示提示听者不会调用 Event 对象的 preventDefault() 方法。默认值: false
    • capture <boolean> Node.js 不会直接使用。添加是为了 API 的完整性。默认值: false
    • signal <AbortSignal> 当调用给定 AbortSignal 对象的 abort() 方法时,将移除该监听器。

type 事件添加新的处理程序。每个给定的 listener 在每个 type 和每个 capture 选项值下仅会被添加一次。

🌐 Adds a new handler for the type event. Any given listener is added only once per type and per capture option value.

如果 once 选项为 truelistener 会在下一次触发 type 事件后被移除。

🌐 If the once option is true, the listener is removed after the next time a type event is dispatched.

capture 选项在 Node.js 中除了按照 EventTarget 规范跟踪已注册的事件监听器外,不会以任何功能方式使用。具体来说,注册 listener 时会将 capture 选项用作键的一部分。每个单独的 listener 可以在 capture = false 的情况下添加一次,也可以在 capture = true 的情况下添加一次。

🌐 The capture option is not used by Node.js in any functional way other than tracking registered event listeners per the EventTarget specification. Specifically, the capture option is used as part of the key when registering a listener. Any individual listener may be added once with capture = false, and once with capture = true.

function handler(event) {}

const target = new EventTarget();
target.addEventListener('foo', handler, { capture: true });  // first
target.addEventListener('foo', handler, { capture: false }); // second

// Removes the second instance of handler
target.removeEventListener('foo', handler);

// Removes the first instance of handler
target.removeEventListener('foo', handler, { capture: true });