Implement an EventEmitter whose on() returns an off handle
Implement an EventEmitter class in JavaScript that allows for subscribing to events, emitting events, and unsubscribing from events. This problem is categorized as medium difficulty and is commonly encountered in interviews for companies like Meta. Understanding event handling and the observer pattern is crucial for frontend developers, making this challenge both relevant and instructive. An event emitter with unsubscribe support follows the observer pattern.
The EventEmitter class should have the following functionalities:
name. This method should return an object with an off method, which when called, removes the listener.name and calls all the registered callbacks with the provided arguments.Your implementation should allow for the dynamic addition and removal of event listeners, ensuring that event callbacks are executed in the order they were added. The emit method should return true if the event has listeners and was successfully emitted, or false otherwise.
Example usage:
const emitter = new EventEmitter();
var sum = 0;
function addTwoNumbers(a, b) {
sum = a + b;
}
const sub = emitter.on('foo', addTwoNumbers);
emitter.emit('foo', 2, 5); // Triggers addTwoNumbers, expecting sum = 7
console.log(sum); // Output: 7
sub.off(); // Unsubscribe the addTwoNumbers listener from 'foo' event
emitter.emit('foo', -3, 9); // Since addTwoNumbers is unsubscribed, sum remains unchanged
console.log(sum); // Output: 7
This task assesses your ability to work with classes, callbacks, and advanced JavaScript concepts such as closures and the observer pattern. Successfully implementing an EventEmitter demonstrates a deep understanding of event-driven programming, a key aspect of many JavaScript applications.