Skip to content

Instantly share code, notes, and snippets.

@cacheflow
Last active January 20, 2017 02:48
Show Gist options
  • Save cacheflow/dea85bac4e8de5cae3fe960bbd503681 to your computer and use it in GitHub Desktop.
Save cacheflow/dea85bac4e8de5cae3fe960bbd503681 to your computer and use it in GitHub Desktop.
class Dispatcher {
constructor() {
this._id = 0
this._cbs = {}
}
register(cb) {
this._cbs[this._id] = cb
return this._id++
}
unregister(id) {
if (this._cbs.hasOwnProperty(id)) {
delete this._cbs[id]
}
}
dispatch(payload) {
for(let id in this._cbs) {
this._cbs[id](payload)
}
}
}
let dispatcher = new Dispatcher()
class Store {
constructor() {
this._littleStore = {}
this._littleStore.state = {}
this._id = 0
this._emitter = new Dispatcher()
}
registerWithDispatcher() {
dispatcher.register((payload) => {
switch(payload.type) {
case "HELLO_WORLD":
this._littleStore["state"][this._id] = payload.text
this._id++
break;
case "GOODBYE_WORLD":
this._littleStore["state"][this._id] = payload.text
this._id++
break;
default:
return
}
this._emitter.dispatch()
})
}
addListener(func) {
return this._emitter.register(func)
}
removeListener(id) {
this._emitter.unregister(id)
}
getState() {
return this._littleStore
}
}
let store = new Store()
store.registerWithDispatcher()
let listenEvent = store.addListener(() => console.log(store.getState()))
store.removeListener(listenEvent)
dispatcher.dispatch({type: "HELLO_WORLD", text: "Hello world!"})
dispatcher.dispatch({type: "GOODBYE_WORLD", text: "Hello world again"})
console.log(store.getState())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment