You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In the observer pattern (also commonly known as the publish-subscribe model), we can observe/subscribe to events emitted by publishers and execute code whenever an event happens.
4
+
5
+
Implement an [`EventEmitter` class](https://nodejs.org/api/events.html#class-eventemitter) similar to the one in [Node.js](https://nodejs.org/api/events.html) that follows such an observer pattern.
6
+
7
+
Example usage of the EventEmitter class:
8
+
9
+
```javascript
10
+
constemitter=newEventEmitter();
11
+
12
+
functionaddTwoNumbers(a, b) {
13
+
console.log(`The sum is ${a + b}`);
14
+
}
15
+
emitter.on('foo', addTwoNumbers);
16
+
emitter.emit('foo', 2, 5);
17
+
// > "The sum is 7"
18
+
19
+
emitter.on('foo', (a, b) =>console.log(`The product is ${a * b}`));
0 commit comments