diff options
author | Thomas <tmashuang@gmail.com> | 2018-04-24 02:22:24 +0800 |
---|---|---|
committer | Thomas <tmashuang@gmail.com> | 2018-04-24 02:22:24 +0800 |
commit | 010092312998e90688e1bfb004eb55c67a337429 (patch) | |
tree | 93a174b2eb7074283d6e43bcc98bc1f2c7925d57 /app/scripts/lib/ComposableObservableStore.js | |
parent | ddece0cc11215b323df96287f39e6758aa559f77 (diff) | |
parent | 74c419f9b65841c2966d1fe3b7414bf11e09e0d8 (diff) | |
download | tangerine-wallet-browser-010092312998e90688e1bfb004eb55c67a337429.tar.gz tangerine-wallet-browser-010092312998e90688e1bfb004eb55c67a337429.tar.zst tangerine-wallet-browser-010092312998e90688e1bfb004eb55c67a337429.zip |
Merge branch 'master' into testing
Diffstat (limited to 'app/scripts/lib/ComposableObservableStore.js')
-rw-r--r-- | app/scripts/lib/ComposableObservableStore.js | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/app/scripts/lib/ComposableObservableStore.js b/app/scripts/lib/ComposableObservableStore.js new file mode 100644 index 000000000..d5ee708a1 --- /dev/null +++ b/app/scripts/lib/ComposableObservableStore.js @@ -0,0 +1,49 @@ +const ObservableStore = require('obs-store') + +/** + * An ObservableStore that can composes a flat + * structure of child stores based on configuration + */ +class ComposableObservableStore extends ObservableStore { + /** + * Create a new store + * + * @param {Object} [initState] - The initial store state + * @param {Object} [config] - Map of internal state keys to child stores + */ + constructor (initState, config) { + super(initState) + this.updateStructure(config) + } + + /** + * Composes a new internal store subscription structure + * + * @param {Object} [config] - Map of internal state keys to child stores + */ + updateStructure (config) { + this.config = config + this.removeAllListeners() + for (const key in config) { + config[key].subscribe((state) => { + this.updateState({ [key]: state }) + }) + } + } + + /** + * Merges all child store state into a single object rather than + * returning an object keyed by child store class name + * + * @returns {Object} - Object containing merged child store state + */ + getFlatState () { + let flatState = {} + for (const key in this.config) { + flatState = { ...flatState, ...this.config[key].getState() } + } + return flatState + } +} + +module.exports = ComposableObservableStore |