Created
March 26, 2018 14:05
-
-
Save brandedoutcast/1c66d99372d2771f9f445c0c23f460b0 to your computer and use it in GitHub Desktop.
Pub Sub Pattern
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 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