EventEmitter is a class of the event module that can be used to raise and handle custom events. This module facilitates communication between objects in Node and is at the core of asynchronous event-driven architecture. This class has properties like on which is used to bind functions on events and emit which fires events.
emit() function
this function is used to create an event and it takes one parameter which is the event name.
const events = require('events')
const eventEmitter = new events.EventEmitter()
eventEmitter.emit('nameOfEvent')
on() function
This function binds an event with an event handler JavaScript function and it takes two parameters:
- name of event to bind
- EventHandler Function
// we require the module events
const EventEmitter = require('events')
const customEmitter = new EventEmitter()
// the event _myEvent_ is bound to the function parameter
customEmitter.on('myEvent', (name, age ) => {
console.log(`My name is ${name} and I am ${age} years old`)
})
//myEvent is triggered
customEmitter.emit('myEvent', 'Grace', 22)
Top comments (0)