Skip to content

Instantly share code, notes, and snippets.

@bloodyowl
Created February 24, 2015 19:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bloodyowl/995160ec0e74d0a18392 to your computer and use it in GitHub Desktop.
Save bloodyowl/995160ec0e74d0a18392 to your computer and use it in GitHub Desktop.
Store.js
export default class Store {
listeners = new Set()
constructor(dispatcher) {
this.reactions = this.getActionHandlers()
this.dispatcher = null
this.dispatchToken = null
this.actionHandler = this.actionHandler.bind(this)
this._getOriginalState()
}
_getOriginalState() {
if(__DOM__) {
const node = document.querySelector(
`[data-storename=${ this.constructor.displayName }]`
)
if(!node) {
return
}
this.state = JSON.parse(node.innerHTML)
// remove the script after we took the data from it
node.parentNode.removeChild(node)
}
}
registerDispatcher(dispatcher) {
this.dispatcher = dispatcher
this.dispatchToken = this.dispatcher.register(this.actionHandler)
}
setState(nextState) {
this.state = {
...this.state,
...nextState,
}
this.emitChange()
}
actionHandler(action){
if(!this.reactions.hasOwnProperty(action.type)) {
return
}
this.reactions[action.type].call(this, action)
}
addChangeListener(func) {
this.listeners.add(func)
}
removeChangeListener(func) {
this.listeners.delete(func)
}
emitChange() {
this.listeners.forEach((value) => {
value()
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment