Junior — Middle
Explain what the EventEmitter mechanism is and how it is used for event handling in applications.
sobes.tech AI
Answer from AI
EventEmitter is a class in Node.js that implements the "observer" pattern for event handling. It allows objects to generate events and subscribe to them to react when they occur.
Using EventEmitter is convenient for asynchronous programming and organizing interaction between parts of an application without tight coupling.
Example of usage:
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
// Subscribing to an event
myEmitter.on('event', () => {
console.log('Event occurred!');
});
// Emitting an event
myEmitter.emit('event');
In this example, an instance of EventEmitter is created, and event listeners subscribe to it. When the emit method is called, all subscribers to this event are notified and perform the corresponding actions.