Skip to content

Instantly share code, notes, and snippets.

@husa
Created Jan 28, 2016
Embed
What would you like to do?
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});
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