|
| 1 | +// In the observer pattern, the source of data itself (the Subject) knows who all are its observers. |
| 2 | +// So, there is no intermediate broker between Subject and Observers. Whereas in pub-sub, the publishers and |
| 3 | +// subscribers are loosely coupled, they are unaware of even the existence of each other |
| 4 | +class PubSub { |
| 5 | + constructor() { |
| 6 | + this.observers = {}; |
| 7 | + } |
| 8 | + // add the observer to listener |
| 9 | + subscribe = (event, cb) => { |
| 10 | + if (this.observers[event]) { |
| 11 | + this.observers[event] = [...this.observers[event], cb]; |
| 12 | + } |
| 13 | + else this.observers[event] = [cb]; |
| 14 | + } |
| 15 | + |
| 16 | + // remove the observer |
| 17 | + unsubscribe = (event) => { |
| 18 | + let { [event]: a, ...rest } = this.observers; |
| 19 | + this.observers = rest; |
| 20 | + } |
| 21 | + |
| 22 | + publish = (event, ...data) => { |
| 23 | + this.observers[event]?.forEach(listener => { |
| 24 | + listener.apply(this, data); |
| 25 | + }) |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +const pubSub = new PubSub(); |
| 30 | + |
| 31 | +pubSub.subscribe("event1", (data) => { |
| 32 | + console.log("First sub : Event1 data", data); |
| 33 | +}); |
| 34 | +pubSub.subscribe("event1", (data) => { |
| 35 | + console.log("Second Sub : Event1 data", data); |
| 36 | +}); |
| 37 | + |
| 38 | +pubSub.subscribe("event2", (data) => { |
| 39 | + console.log("Event2 data", data); |
| 40 | +}); |
| 41 | +pubSub.publish("event1", { name: "IV1" }); |
| 42 | +pubSub.publish("event2", { name: "IV2" }); |
| 43 | +pubSub.unsubscribe("event1"); |
| 44 | +pubSub.publish("event1", { name: "IV23" }); |
| 45 | + |
| 46 | + |
| 47 | +// OUTPUT |
| 48 | + |
| 49 | +// First sub : Event1 data |
| 50 | +// {name: "IV1"} |
| 51 | +// Second Sub : Event1 data |
| 52 | +// {name: "IV1"} |
| 53 | +// Event2 data |
| 54 | +// {name: "IV2"} |
| 55 | + |
| 56 | + |
| 57 | +// Observer | PUb SUb |
| 58 | +// ---------------- -------- |
| 59 | +// synchronous | async |
| 60 | +// subject knows its observers | subscriber and publisher dont know about each others existance |
0 commit comments