Skip to content

Instantly share code, notes, and snippets.

@night-fury-rider
Last active April 22, 2025 12:21
Show Gist options
  • Save night-fury-rider/f10093cdfffbbac12665da76e3692479 to your computer and use it in GitHub Desktop.
Save night-fury-rider/f10093cdfffbbac12665da76e3692479 to your computer and use it in GitHub Desktop.
Design Pattern - Pub/Sub
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