Skip to content

Instantly share code, notes, and snippets.

@jossmac
Last active November 5, 2018 00:59
Show Gist options
  • Save jossmac/98834ab4461c381fec62f58183a998b1 to your computer and use it in GitHub Desktop.
Save jossmac/98834ab4461c381fec62f58183a998b1 to your computer and use it in GitHub Desktop.
Store class with subscribers
export default class Store {
listeners = []
store = []
add = (data) => {
const id = uniqueId()
const item = { id, data }
this.store.push(item)
this.publish()
}
remove = (id) => {
this.store = this.store.filter(item => item.id !== id)
this.publish()
}
subscribe = (fn) => {
this.listeners.push(fn)
}
unsubscribe = (rm) => {
this.listeners = this.listeners.filter(fn => fn !== rm)
}
publish = () => {
this.listeners.forEach(fn => fn(this.store))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment