Mark As Completed Discussion

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!

Question

Try to solve this here or in Interactive Mode.

How do I practice this challenge?

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Here's our guided, illustrated walk-through.

How do I use this guide?