Skip to content

Instantly share code, notes, and snippets.

@brandedoutcast
Created March 26, 2018 14:05
Show Gist options
  • Save brandedoutcast/1c66d99372d2771f9f445c0c23f460b0 to your computer and use it in GitHub Desktop.
Save brandedoutcast/1c66d99372d2771f9f445c0c23f460b0 to your computer and use it in GitHub Desktop.
Pub Sub Pattern
class PubSub {
constructor() {
this.events = []
}
on(name, handler) {
this.events[name] = this.events[name] || []
this.events[name].push(handler)
}
off(name, handler) {
if (this.events[name]) {
let handlerIndex = this.events[name].findIndex(h => h === handler)
if (handlerIndex >= 0) {
this.events[name].splice(handlerIndex, 1)
}
}
}
emit(name, data) {
if (this.events[name]) {
this.events[name].forEach(h => h(data))
}
}
}
export const PUBSUB = new PubSub()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment