The event-driven architecture allows asynchronous/synchronous programming, and your application becomes able to perform non-blocking/blocking operations.
EventEmitter class is part of the events module in Node.js.
EventEmitter Methods : .on, .emit (Triggers the event), .once(executes only once), removeListener(Removes Specific Event), .off etc..
Disadvantages : Complex, Difficult to find error, Confusing, etc..
const EventEmitter = require('events');
// Initializing event emitter instances
var eventEmitter = new EventEmitter();
// Declaring listener fun1 to myEvent1
var function1 = (msg) => {
console.log("Message from function1: " + msg);
};
// Declaring listener fun2 to myEvent2
var function2 = (msg) => {
console.log("Message from function2: " + msg);
};
// Listening to myEvent with fun1 and fun2
eventEmitter.addListener('myEvent', function1);
// fun2 will be inserted in front of listeners array
eventEmitter.prependListener('myEvent', function2);
// Listing listeners
console.log(eventEmitter.listeners('myEvent'));
// Count the listeners registered to myEvent
console.log(eventEmitter.listenerCount('myEvent'));
// Triggering myEvent
eventEmitter.emit('myEvent', 'Event occurred');
No comments:
Post a Comment