Skip to content

Instantly share code, notes, and snippets.

@the-architect
Created April 12, 2017 20:15
Show Gist options
  • Save the-architect/9a020d7e5f6aeb88c73d9a9805916d9f to your computer and use it in GitHub Desktop.
Save the-architect/9a020d7e5f6aeb88c73d9a9805916d9f to your computer and use it in GitHub Desktop.
ES6 Simple global PubSub system
export class PubSub {
constructor (){
this.subscriptions = {};
}
subscribe (event, subscriber) {
if (typeof this.subscriptions[event] === 'undefined') {
this.subscriptions[event] = new Set();
}
this.subscriptions[event].add(subscriber);
}
fire (event, payload) {
let subscribers = this.subscriptions[event];
if (subscribers) {
subscribers.forEach((subscriber) => {
subscriber(payload, event);
});
}
}
}
if (typeof window.PubSub === 'undefined') {
window.PubSub = new PubSub();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment