Good morning! Here's our prompt for today.
In modern applications, we often need asynchronous functions. These wait for responses from operations with unknown completion times. So many frameworks use an event-driven architecture.
Certain objects called emitters emit named events. This triggers listener functions to execute.
Each event has an ID. So listeners know which event to subscribe to. If that event fires, the listener is called.
Can you implement a class to enable this? It should:
- Emit events other code can subscribe to
- Subscribe to events, getting their outputs
For example:
JAVASCRIPT
1// Create emitter
2const emitter = new EventEmitter();
3
4// Subscribe to event
5emitter.subscribe('event1', callback1);
The emit method triggers events:
JAVASCRIPT
1emitter.emit('event1', 1, 2);
This passes arguments to listeners.
JAVASCRIPT
1const emitter = new EventEmitter();
2
3emitter.subscribe('message', (msg) => {
4 console.log('Received message:', msg);
5});
6
7emitter.emit('message', 'Hello World!');
8
9// Listener outputs:
10// Received message: Hello World!

Try to solve this here or in Interactive Mode.
How do I practice this challenge?
xxxxxxxxxx
31
class EventEmitter {
subscriptions = new Map();
subscribe(eventName, callback) {
if (!this.subscriptions.has(eventName)) {
this.subscriptions.set(eventName, new Set());
}
const subscriptions = this.subscriptions.get(eventName);
const callbackObj = { callback };
subscriptions.add(callbackObj);
return {
release: () => {
subscriptions.delete(callbackObj);
if (subscriptions.size === 0) {
delete this.subscriptions.eventName;
}
},
};
}
emit(eventName, args) {
const subscriptions = this.subscriptions.get(eventName);
if (subscriptions) {
subscriptions.forEach((cbObj) => {
cbObj.callback.apply(this, args);
});
}
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Here's our guided, illustrated walk-through.
How do I use this guide?