Skip to content

Instantly share code, notes, and snippets.

@jremi
Created November 15, 2020 20:08
Show Gist options
  • Save jremi/545ce4fb850ab73d214dba7ab5710138 to your computer and use it in GitHub Desktop.
Save jremi/545ce4fb850ab73d214dba7ab5710138 to your computer and use it in GitHub Desktop.
Super simple es6 class pubsub
class Publisher {
constructor() {
this.subscribers = [];
}
addSubscriber(subscriberInstance) {
this.subscribers.push(subscriberInstance);
}
emit(eventName, payload) {
this.subscribers.forEach(subscriber => {
if(subscriber.subscriptions[eventName]) {
subscriber.subscriptions[eventName](payload)
}
})
}
}
class Subscriber {
constructor() {
this.subscriptions = {};
}
on(eventName, callback) {
this.subscriptions[eventName] = callback;
}
}
const publisher = new Publisher();
const subscriber1 = new Subscriber();
const subscriber2 = new Subscriber();
publisher.addSubscriber(subscriber1);
publisher.addSubscriber(subscriber2);
subscriber1.on("event/newNotification", (payload) => {
console.log("Fired subscriber1! event/newNotification", payload);
});
subscriber2.on("event/newNotification", (payload) => {
console.log("Fired subscriber2! event/newNotification", payload);
});
publisher.emit('event/newNotification', {
foo: 'bar',
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment