Created
November 15, 2020 20:08
-
-
Save jremi/545ce4fb850ab73d214dba7ab5710138 to your computer and use it in GitHub Desktop.
Super simple es6 class pubsub
This file contains 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 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