improve store and reducers

This commit is contained in:
Shin'ya Ueoka 2017-09-14 21:14:13 +09:00
parent 9dc02b2fd8
commit c42ac8fac4
3 changed files with 29 additions and 7 deletions

View file

@ -3,21 +3,38 @@ class Store {
this.reducer = reducer;
this.catcher = catcher;
this.state = this.reducer(undefined, {});
this.subscribers = [];
}
dispatch(action) {
if (action instanceof Promise) {
action.then((a) => {
this.state = this.reducer(this.state, a);
this.transitNext(a);
}).catch(this.catcher)
} else {
try {
this.state = this.reducer(this.state, action);
this.transitNext(action);
} catch (e) {
this.catcher(e);
}
}
}
getState() {
return this.state;
}
subscribe(callback) {
this.subscribers.push(callback);
}
transitNext(action) {
let newState = this.reducer(this.state, action);
if (JSON.stringify(this.state) !== JSON.stringify(newState)) {
this.state = newState;
this.subscribers.forEach(f => f.call())
}
}
}
const empty = () => {};