Skip to content

Instantly share code, notes, and snippets.

@tyler-vs
Created March 24, 2023 15:23
Show Gist options
  • Save tyler-vs/fd095e7cd3be00cd5cf6783dd0f3b52a to your computer and use it in GitHub Desktop.
Save tyler-vs/fd095e7cd3be00cd5cf6783dd0f3b52a to your computer and use it in GitHub Desktop.
class Pubsub {
constructor() {
this.events = {};
}
subscription (eventName, func) {
return {
subscribe: () => {
if (this.events[eventName]) {
this.events[eventName].push(func);
console.log(`${func.name} has subscribed to ${eventName} Topic!`)
} else {
this.events[eventName] = [func];
console.log(`${func.name} has subscribed to ${eventName} Topic!`)
}
},
unsubscribe: () => {
if(this.events[eventName]){
this.events[eventName] = this.events[eventName].filter((subscriber) => subscriber !== func);
console.log(`${func.name} has unsubscribed from ${eventName} Topic!`)
}
}
}
}
publish(eventName, ...args) {
const funcs = this.events[eventName];
if (Array.isArray(funcs)) {
funcs.forEach((func) => {
func.apply(null, args);
});
}
}
}
const speak = (param) => {
console.log(`I am ${param}`);
};
const greetAll = (x, y, z) => {
console.log(`Hello ${x}, ${y}, ${z}`);
};
const pubsub = new Pubsub();
pubsub.subscription("greet", greetAll).subscribe() // prints greetAll has subscribed to greet Topic!
pubsub.subscription("sayName", speak).subscribe() // prints speak has subscribed to sayName Topic!
pubsub.subscription("sayName", greetAll).unsubscribe() // prints greetAll has unsubscribed from sayName Topic!
pubsub.publish("greet", "Lawrence Eagles", "John Doe", "Jane Doe"); // prints Hello Lawrence Eagles, John Doe, Jane Doe
pubsub.publish("sayName", "Lawrence Eagles"); // prints I am Lawrence Eagles
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment