Implement an EventEmitter class. Code can subscribe to named events with on, unsubscribe with off, and trigger every subscriber of an event with emit.
const emitter = new EventEmitter();
function greet(name) {
console.log(`Hello, ${name}`);
}
emitter.on('join', greet);
emitter.emit('join', 'Ada'); // logs "Hello, Ada", returns true
emitter.off('join', greet);
emitter.emit('join', 'Grace'); // logs nothing, returns false
| Method | Behaviour |
|---|---|
on(eventName, listener) | Adds listener to the end of the list for eventName. Returns the emitter so calls can be chained. |
off(eventName, listener) | Removes one registration of listener: the most recently added one. Unknown events or listeners are ignored. Returns the emitter. |
emit(eventName, ...args) | Calls every listener for eventName synchronously, in registration order, with args. Returns true if the event had listeners, otherwise false. |
this set to the emitter.emit must not affect the listeners called by that emit.Object.prototype (an event called "toString" or "constructor" must work).once?Spotted a mistake or a rights concern? Report an issue