Community

Start a Thread


Notifications
Subscribe You’re not receiving notifications from this thread.

Create Event Emitter (Main Thread)

Here is the interview question prompt, presented for reference.

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:

// Create emitter
const emitter = new EventEmitter(); 

// Subscribe to event
emitter.subscribe('event1', callback1);

The emit method triggers events:

emitter.emit('event1', 1, 2);

This passes arguments to listeners.

const emitter = new EventEmitter();

emitter.subscribe('message', (msg) => {
  console.log('Received message:', msg); 
});

emitter.emit('message', 'Hello World!');

// Listener outputs:
// Received message: Hello World!

![cover](https://storage.googleapis.com/algodailyrandomassets/curriculum/frontend/interview-questions/create-event-emitter.jpg)

You can see the full challenge with visuals at this link.

Challenges • Asked almost 3 years ago by Jake from AlgoDaily

Jake from AlgoDaily Commented on Jun 04, 2022:

This is the main discussion thread generated for Create Event Emitter (Main Thread).