NodeJS - eventTarget.dispatchEvent() method


The eventTarget.dispatchEvent() method is used to dispatch an Event at the specified EventTarget, invoking the affected EventListeners in the order in which they have been added.

This method belongs to EventTarget class of node:events module.

Syntax

Following is the syntax of the NodeJs eventTarget.dispatchEvent() method −

eventTarget.dispatchEvent(event)

Parameters

This method accepts only one parameter.

  • event: This parameter holds the Event object to be dispatched.

Return value

This methods return value is false if at least one of the event handlers which are handling that specific event called Event.preventDefault() method else, it returns true.

Example 1

Following is the basic example of the NodeJs eventTarget.dispatchEvent() Method.

Initially, we imported the node:events module. Then we created an Event with a constructor. Then we added a listener to the event named event. Then we dispatched the Event by calling eventTarget.dispatchEvent() with event as a parameter to it.

const { EventEmitter, listenerCount } = require('node:events');
const { eventNames } = require('node:process');

const eventtarget = new EventTarget();

const event = new Event('build');

// Listen for the event.
eventtarget.addEventListener('build', (event) => { console.log(Hello) }, false);

// Dispatch the event.
eventtarget.dispatchEvent(event);

Output

Hello

Example 2

In this program, it doesn't directly use dispatchEvent() but it works for a similar purpose.

const { EventEmitter } = require('events');

class MyEmitter extends EventEmitter {}

const myEmitter = new MyEmitter();

myEmitter.on('event', () => {
  console.log('an event occurred!');
});

myEmitter.emit('event');

Output

an event occurred!
nodejs_events.htm
Advertisements