EventTarget and Event API
History
EventTarget and Event classes are now available as globals.The EventTarget and Event objects are a Node.js-specific implementation
of the EventTarget Web API that are exposed by some Node.js core APIs.
const target = new EventTarget(); target.addEventListener('foo', (event) => { console.log('foo event happened!'); });
There are two key differences between the Node.js EventTarget and the
EventTarget Web API:
- Whereas DOM
EventTargetinstances may be hierarchical, there is no concept of hierarchy and event propagation in Node.js. That is, an event dispatched to anEventTargetdoes not propagate through a hierarchy of nested target objects that may each have their own set of handlers for the event. - In the Node.js
EventTarget, if an event listener is an async function or returns aPromise, and the returnedPromiserejects, the rejection is automatically captured and handled the same way as a listener that throws synchronously (seeEventTargeterror handling for details).
The NodeEventTarget object implements a modified subset of the
EventEmitter API that allows it to closely emulate an EventEmitter in
certain situations. A NodeEventTarget is not an instance of EventEmitter
and cannot be used in place of an EventEmitter in most cases.
- Unlike
EventEmitter, any givenlistenercan be registered at most once per eventtype. Attempts to register alistenermultiple times are ignored. - The
NodeEventTargetdoes not emulate the fullEventEmitterAPI. Specifically theprependListener(),prependOnceListener(),rawListeners(), anderrorMonitorAPIs are not emulated. The'newListener'and'removeListener'events will also not be emitted. - The
NodeEventTargetdoes not implement any special default behavior for events with type'error'. - The
NodeEventTargetsupportsEventListenerobjects as well as functions as handlers for all event types.
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 });
When a registered event listener throws (or returns a Promise that rejects),
by default the error is treated as an uncaught exception on
process.nextTick(). This means uncaught exceptions in EventTargets will
terminate the Node.js process by default.
Throwing within an event listener will not stop the other registered handlers from being invoked.
The EventTarget does not implement any special default handling for 'error'
type events like EventEmitter.
Currently errors are first forwarded to the process.on('error') event
before reaching process.on('uncaughtException'). This behavior is
deprecated and will change in a future release to align EventTarget with
other Node.js APIs. Any code relying on the process.on('error') event should
be aligned with the new behavior.
Event
History
Event class is now available through the global object.The Event object is an adaptation of the Event Web API. Instances
are created internally by Node.js.
booleanfalse.This is not used in Node.js and is provided purely for completeness.
event.stopPropagation() instead.booleanAlias for event.stopPropagation() if set to true. This is not used
in Node.js and is provided purely for completeness.
booleancancelable option.booleanfalse.This is not used in Node.js and is provided purely for completeness.
event.composedPath(): void
Returns an array containing the current EventTarget as the only entry or
empty if the event is not being dispatched. This is not used in
Node.js and is provided purely for completeness.
EventTargetEventTarget dispatching the event.Alias for event.target.
booleanIs true if cancelable is true and event.preventDefault() has been
called.
number0 while an event is not being dispatched, 2 while
it is being dispatched.This is not used in Node.js and is provided purely for completeness.
event.initEvent(type, bubbles?, cancelable?): void
Redundant with event constructors and incapable of setting composed.
This is not used in Node.js and is provided purely for completeness.
booleanThe AbortSignal "abort" event is emitted with isTrusted set to true. The
value is false in all other cases.
event.preventDefault(): void
Sets the defaultPrevented property to true if cancelable is true.
event.defaultPrevented instead.booleanThe value of event.returnValue is always the opposite of event.defaultPrevented.
This is not used in Node.js and is provided purely for completeness.
event.target instead.EventTargetEventTarget dispatching the event.Alias for event.target.
event.stopImmediatePropagation(): void
Stops the invocation of event listeners after the current one completes.
event.stopPropagation(): void
This is not used in Node.js and is provided purely for completeness.
EventTargetEventTarget dispatching the event.numberThe millisecond timestamp when the Event object was created.
stringThe event type identifier.
EventTarget
History
EventTarget class is now available through the global object.eventTarget.addEventListener(type, listener, options?): void
stringFunction | EventListenerObjectbooleantrue, the listener is automatically removed
when it is first invoked. Default: false.booleantrue, serves as a hint that the listener will
not call the Event object's preventDefault() method.
Default: false.booleanfalse.AbortSignalabort() method is called.Adds a new handler for the type event. Any given listener is added
only once per type and per capture option value.
If the once option is true, the listener is removed after the
next time a type event is dispatched.
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 });
eventTarget.dispatchEvent(event): boolean
Dispatches the event to the list of handlers for event.type.
The registered event listeners is synchronously invoked in the order they were registered.
eventTarget.removeEventListener(type, listener, options?): void
Removes the listener from the list of handlers for event type.
CustomEvent
History
--experimental-global-customevent CLI flag.class CustomEvent extends Event
The CustomEvent object is an adaptation of the CustomEvent Web API.
Instances are created internally by Node.js.
event.detail
History
anyRead-only.
class NodeEventTarget extends EventTarget
The NodeEventTarget is a Node.js-specific extension to EventTarget
that emulates a subset of the EventEmitter API.
nodeEventTarget.addListener(type, listener): EventTarget
Node.js-specific extension to the EventTarget class that emulates the
equivalent EventEmitter API. The only difference between addListener() and
addEventListener() is that addListener() will return a reference to the
EventTarget.
nodeEventTarget.emit(type, arg): boolean
Node.js-specific extension to the EventTarget class that dispatches the
arg to the list of handlers for type.
nodeEventTarget.eventNames(): string[]
string[]Node.js-specific extension to the EventTarget class that returns an array
of event type names for which event listeners are registered.
nodeEventTarget.listenerCount(type): number
Node.js-specific extension to the EventTarget class that returns the number
of event listeners registered for the type.
nodeEventTarget.setMaxListeners(n): void
numberNode.js-specific extension to the EventTarget class that sets the number
of max event listeners as n.
nodeEventTarget.getMaxListeners(): number
numberNode.js-specific extension to the EventTarget class that returns the number
of max event listeners.
nodeEventTarget.off(type, listener, options?): EventTarget
Node.js-specific alias for eventTarget.removeEventListener().
nodeEventTarget.on(type, listener): EventTarget
Node.js-specific alias for eventTarget.addEventListener().
nodeEventTarget.once(type, listener): EventTarget
Node.js-specific extension to the EventTarget class that adds a once
listener for the given event type. This is equivalent to calling on
with the once option set to true.
nodeEventTarget.removeAllListeners(type?): EventTarget
stringEventTargetNode.js-specific extension to the EventTarget class. If type is specified,
removes all registered listeners for type, otherwise removes all registered
listeners.
nodeEventTarget.removeListener(type, listener, options?): EventTarget
Node.js-specific extension to the EventTarget class that removes the
listener for the given type. The only difference between removeListener()
and removeEventListener() is that removeListener() will return a reference
to the EventTarget.