An event emitter is an object that can emit events and register listeners for those events. Event emitters are often used in Node.js to implement the publish-subscribe pattern, where one or more objects publish events and zero or more objects subscribe to those events and execute some code when the events are emitted.
In Node.js, the EventEmitter
class from the events
module provides a base class for creating event emitters. This class has methods for emitting events and registering listeners, such as emit()
, on()
, and once()
.
You can create an event emitter by using the EventEmitter
class from the events
module. This class allows you to create objects that can emit events and register listeners for those events.
Here is an example of how to create an event emitter:
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
To emit an event, you can use the emit()
method of the event emitter object. This method takes the name of the event as the first argument, and any additional arguments as additional arguments.
For example:
myEmitter.emit('event', 'arg1', 'arg2');
To register a listener for an event, you can use the on()
method of the event emitter object. This method takes the name of the event as the first argument, and a callback function as the second argument. The callback function will be called every time the event is emitted.
For example:
myEmitter.on('event', (arg1, arg2) => {
console.log(arg1, arg2);
});