📌  相关文章
📜  EventEmitter 和 NodeEventTarget 的区别

📅  最后修改于: 2021-09-15 01:56:42             🧑  作者: Mango

EventEmitter:所有EventEmitter在添加新侦听器时发出事件 ‘ newListener ‘,在删除现有侦听器时发出事件 ‘ removeListener ‘。它由 events 模块定义和公开:

要导入EventEmitter ,请使用以下导入语句:

const EventEmitter = require('events');

NodeEventTarget: EventTarget和 Event 对象是 EventTarget Web API 的 Node.js 特定实现,由一些 Node.js核心 API 公开。

EventEmitterNodeEventTarget之间的区别

Event Emitter Node Event Target
It is inherited from the events Module of JavaScript. It is a modified subset of EventEmitter API and inherited from it.
It implements is-a relationship with the events Module. It implements is-a relationship with the EventTarget API.
In eventEmitter, for the same event, we can allow multiple listeners to be registered. Any listener can be registered once per event type and it gets ignored if attempted to register a listener multiple times.
It emulates the most from Events such as ‘error’, ‘Classes’, Emits, etc.  It does not emulate the full EventEmitter APIs like prependListener(), prependOnceListener(), rawListeners(), etc.
Its default behavior is to log information and end the current execution. For ‘error‘ type events, it does not implement any default behavior.
 If an error occurs within an EventEmitter instance, then the typical action is for an ‘error’ event to be emitted.  It supports EventListener objects and functions as handlers for all event types.
 All EventEmitter emit the event ‘newListener’, when new listeners are added and ‘removeListener’ when listeners are removed. It isn’t an instance of EventEmitter and in most cases, it can’t be used in place of an EventEmitter.

Syntax:

emitter.once(
  eventName, listener)

Syntax:

nodeEventTarget.once(
  type, listener[, options])

参考: https://nodejs.org/api/events.html#events_nodeeventtarget_vs_eventemitter