let's talk more about events in node
Node.js has ‘events’ module which emits named events that can cause corresponding functions or callbacks to be called
Functions(Callbacks) listen or subscribe to a particular event to occur and when that event triggers, all the callbacks subscribed to that event are fired one by one in order to which they were registered.
The event can be emitted or listen to an event with the help of EventEmitter.
const EventEmitter=require('events');
var eventEmitter=new EventEmitter();
the event has two method :
- on
- Emit
const event = require('events');
class Dog extends event.EventEmitter { }
const dog = new Dog();
dog.on('bark', () => {
console.log('Woof! Woof!');
});
dog.emit('bark');
and there are more methods to use
- eventNames: Returns an array of strings of the assigned events.
- once: Event listener that will be triggered only once.
- removeListener: Remove a specific listener.
- removeAllListeners: Remove all listeners from the event.
let me see how you use them :D