Created
April 12, 2017 20:15
-
-
Save the-architect/9a020d7e5f6aeb88c73d9a9805916d9f to your computer and use it in GitHub Desktop.
ES6 Simple global PubSub system
This file contains hidden or 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
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