Last active
April 22, 2025 12:21
-
-
Save night-fury-rider/f10093cdfffbbac12665da76e3692479 to your computer and use it in GitHub Desktop.
Design Pattern - Pub/Sub
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PubSub { | |
constructor() { | |
this.events = {}; | |
} | |
subscribe(eventName, callback) { | |
if (!this.events[eventName]) { | |
this.events[eventName] = []; | |
} | |
this.events[eventName].push(callback); | |
return () => this.unsubscribe(eventName, callback); | |
} | |
unsubscribe(eventName, callback) { | |
if (this.events[eventName]) { | |
this.events[eventName] = this.events[eventName].filter( | |
(cb) => cb === callback | |
); | |
} | |
} | |
publise(eventName, data) { | |
if (this.events[eventName]) { | |
this.events[eventName].forEach((callback) => callback(data)); | |
} | |
} | |
} | |
const pubSub = new PubSub(); | |
const lockProductPrice = (product) => { | |
console.log(`${product.name} is reserved at ₹ ${product.price}`); | |
}; | |
const updateCartValue = (product) => { | |
console.log(`Cart total is increased by ₹ ${product.price}`); | |
}; | |
pubSub.subscribe("cart:add", lockProductPrice); | |
pubSub.subscribe("cart:add", updateCartValue); | |
const product1 = { | |
name: "Earphone", | |
price: 2500, | |
}; | |
const product2 = { | |
name: "Keyboard", | |
price: 1100, | |
}; | |
pubSub.publise("cart:add", product1); | |
pubSub.publise("cart:add", product2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment