Created
January 28, 2016 20:21
-
-
Save husa/4833f9dd7dfb39295a83 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
const _state = Symbol('previous_state'); | |
const _listeners = Symbol('listeners'); | |
class Store { | |
constructor(state = {}) { | |
this[_state] = {}; | |
this[_listeners] = []; | |
this.setState(state); | |
} | |
setState (state = {}) { | |
state = Object.assign({}, this[_state], state); | |
this[_state] = state; | |
this.dispatch(state); | |
return this; | |
} | |
getState () { | |
return Object.assign({}, this[_state]); | |
} | |
dispatch (state) { | |
if (!this[_listeners].length) return; | |
state = state || this[_state]; | |
this[_listeners].slice().forEach(listener => listener()); | |
} | |
subscribe (listener) { | |
this[_listeners].push(listener); | |
} | |
unsubscribe (listener = null) { | |
if (listener == null) { | |
this[_listeners] = []; | |
} | |
let listeners = this[_listeners]; | |
const index = listeners.indexOf(listener) | |
listeners.splice(index, 1); | |
} | |
} | |
// Usage | |
S = new Store({a:10}); | |
let listener = () => { | |
console.log('change'); | |
let state = S.getState(); | |
console.log(state) | |
} | |
S.subscribe(listener); | |
S.setState({b:20}); | |
S.setState({a:11}); | |
S.unsubscribe(listener); | |
S.setState({a:12}); | |
This file contains hidden or 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 TimerStore extends Store { | |
constructor() { | |
super(...arguments); | |
this.updateStateOnInterval(); | |
} | |
updateStateOnInterval () { | |
this._interval = setInterval(() => { | |
let timer = this.getState().timer; | |
this.setState({timer: ++timer}); | |
}, 1000); | |
} | |
} | |
let ts = new TimerStore({timer: 0}); | |
let listener2 = () => console.log(ts.getState()); | |
ts.subscribe(listener2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment