Mark As Completed Discussion

The emit Method: Triggering the Events

Triggering the Events

Emitting to All Subscribers

The emit method's job is to trigger the event and call all the associated callbacks. It loops through each of the subscriptions and invokes the stored callback functions:

JAVASCRIPT
1emit(eventName, ...args) {
2    const subscriptions = this.subscriptions.get(eventName);
3    if (subscriptions) {
4        subscriptions.forEach((cbObj) => {
5            cbObj.callback.apply(this, args);
6        });
7    }
8}

The ...args syntax allows us to pass any number of arguments to the callback functions. This offers flexibility in what data can be sent when an event is emitted.

The Complete Solution

Putting all these pieces together, we construct our EventEmitter class:

JAVASCRIPT
1class EventEmitter {
2    subscriptions = new Map();
3
4    subscribe(eventName, callback) {
5        if (!this.subscriptions.has(eventName)) {
6            this.subscriptions.set(eventName, new Set());
7        }
8        const subscriptions = this.subscriptions.get(eventName);
9        const callbackObj = { callback };
10        subscriptions.add(callbackObj);
11
12        return {
13            release: () => {
14                subscriptions.delete(callbackObj);
15                if (subscriptions.size === 0) {
16                    delete this.subscriptions.eventName;
17                }
18            },
19        };
20    }
21
22    emit(eventName, ...args) {
23        const subscriptions = this.subscriptions.get(eventName);
24        if (subscriptions) {
25            subscriptions.forEach((cbObj) => {
26                cbObj.callback.apply(this, args);
27            });
28        }
29    }
30}