NodeJS - emitter.emit() Method


The method emitter.emit() will synchronously calls every listeners in the order they were registered to an event named eventName and also by passing the arguments to each listener function.

This method belongs to Eventemitter class is an inbuilt class of node:events module.

Syntax

Following is the syntax of the NodeJs emitter.emit() method −

emitter.emit(eventName[, args])

Parameters

This method accepts two parameters listed below −

  • eventName: This is the first parameter of the method and it holds the name of the event. It can be either string or a symbol.
  • args: (Optional) This parameter holds a set of arguments that can be passed to the listener functions.

Return value

(Boolean) This method returns true if the event had listeners and false if the event doesnt have listeners.

Example 1

The following is the basic example of the NodeJs emitter.emit() Method.

Here, we have passed args to myEmitter.emit() method. the args will be passed to the listener functions and then prints the complete message.

const EventEmitter = require('node:events');
const myEmitter = new EventEmitter();

function f1(arg1, arg2){
  console.log(`${arg1} to ${arg2}`);
}

myEmitter.on('myEvent', f1);

myEmitter.emit("myEvent", 'Welcome', 'Tutorialspoint', 'Bye');

Output

The above program produces the following output −

Welcome to Tutorialspoint

Example 2

First, We created a function func1 with a message inside it. Then we called the emitter.addListener() method with an eventName passed as the first parameter and passed the (func1) to the listener parameter of the method by calling the myEmitter.emit() method with the eventName. As we havent passed any args here. Since the eventName had a listener, the myEmitter.emit() method will return the listener function.

const EventEmitter = require('node:events');
const myEmitter = new EventEmitter();

function f1() {
  console.log("Heya!, i'm function1");
}

myEmitter.addListener("myEvent", f1)

myEmitter.emit("myEvent"); 

Output

The above program produces the following output −

Heya!, i'm function1

Example 3

In this program, we have used the spread operator () to extract every args we passed. so all the args will be extracted and will be passed to the listener function.

const EventEmitter = require('node:events');
const myEmitter = new EventEmitter();

function f1(...args){
  const teams = args.join(', ');
  console.log(`Some International cricket teams are ${teams}.`);
}

myEmitter.on('myEvent', f1);

myEmitter.emit("myEvent", 'India', 'Pakistan', 'Australia', 'England');

Output

The above program produces the following output −

Some International cricket teams are India, Pakistan, Australia, England.
nodejs_events.htm
Advertisements