Last active
November 5, 2018 00:59
-
-
Save jossmac/98834ab4461c381fec62f58183a998b1 to your computer and use it in GitHub Desktop.
Store class with subscribers
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
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