From c42ac8fac48f9d56b54af4818917082fda9af21e Mon Sep 17 00:00:00 2001 From: Shin'ya Ueoka Date: Thu, 14 Sep 2017 21:14:13 +0900 Subject: [PATCH] improve store and reducers --- src/background/index.js | 8 +++----- src/reducers/index.js | 7 +++++++ src/store/index.js | 21 +++++++++++++++++++-- 3 files changed, 29 insertions(+), 7 deletions(-) create mode 100644 src/reducers/index.js diff --git a/src/background/index.js b/src/background/index.js index 0c3adce..e9757b9 100644 --- a/src/background/index.js +++ b/src/background/index.js @@ -2,12 +2,12 @@ import * as keys from './keys'; import * as inputActions from '../actions/input'; import * as operationActions from '../actions/operation'; import backgroundReducers from '../reducers/background'; +import reducers from '../reducers'; import commandReducer from '../reducers/command'; import inputReducers from '../reducers/input'; import * as store from '../store' -const emptyReducer = (state) => state; -const emptyStore = store.createStore(emptyReducer, (e) => { +const backgroundStore = store.createStore(reducers, (e) => { console.error('Vim-Vixen:', e); }); let inputState = inputReducers(undefined, {}); @@ -27,9 +27,7 @@ const keyQueueChanged = (sender, prevState, state) => { return Promise.resolve(); } let action = keys.defaultKeymap[matched]; - emptyStore.dispatch(operationActions.exec(action, sender), (e) => { - console.error('Vim-Vixen:', e); - }); + backgroundStore.dispatch(operationActions.exec(action, sender)); return handleMessage(inputActions.clearKeys(), sender).then(() => { return backgroundReducers(undefined, action, sender).then(() => { return browser.tabs.sendMessage(sender.tab.id, action); diff --git a/src/reducers/index.js b/src/reducers/index.js new file mode 100644 index 0000000..d49af7d --- /dev/null +++ b/src/reducers/index.js @@ -0,0 +1,7 @@ +const defaultState = { +}; + +export default function reducer(state = defaultState/*, action = {}*/) { + return Object.assign({}, state, { + }); +} diff --git a/src/store/index.js b/src/store/index.js index bcb65d6..841fd17 100644 --- a/src/store/index.js +++ b/src/store/index.js @@ -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 = () => {};