diff options
author | Shin'ya Ueoka <ueokande@i-beam.org> | 2017-09-16 23:32:19 +0900 |
---|---|---|
committer | Shin'ya Ueoka <ueokande@i-beam.org> | 2017-09-16 23:32:19 +0900 |
commit | c5529958d53146c8c6826673abe6431a19f1924d (patch) | |
tree | 4952c7ac1ded91d52fd6e424c229022b61b67aa3 /src/store | |
parent | b2cddcd69b4ae06770d66808624fc43f3dcbcb0e (diff) | |
parent | ae394e28c0cbc8710d4937238c97328afddbca0f (diff) |
Merge branch 'more-redux'
Diffstat (limited to 'src/store')
-rw-r--r-- | src/store/index.js | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/src/store/index.js b/src/store/index.js new file mode 100644 index 0000000..2d08296 --- /dev/null +++ b/src/store/index.js @@ -0,0 +1,51 @@ +class Store { + constructor(reducer, catcher) { + this.reducer = reducer; + this.catcher = catcher; + this.subscribers = []; + try { + this.state = this.reducer(undefined, {}); + } catch (e) { + catcher(e); + } + } + + dispatch(action, sender) { + if (action instanceof Promise) { + action.then((a) => { + this.transitNext(a, sender); + }).catch((e) => { + this.catcher(e, sender); + }); + } else { + try { + this.transitNext(action, sender); + } catch (e) { + this.catcher(e, sender); + } + } + return action + } + + getState() { + return this.state; + } + + subscribe(callback) { + this.subscribers.push(callback); + } + + transitNext(action, sender) { + let newState = this.reducer(this.state, action); + if (JSON.stringify(this.state) !== JSON.stringify(newState)) { + this.state = newState; + this.subscribers.forEach(f => f(sender)); + } + } +} + +const empty = () => {}; + +export function createStore(reducer, catcher = empty) { + return new Store(reducer, catcher); +} |