diff options
author | Dan Finlay <542863+danfinlay@users.noreply.github.com> | 2018-04-14 02:57:19 +0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2018-04-14 02:57:19 +0800 |
commit | 3afe76bcba5eb1b84c748b13b61d1a22bed40bd3 (patch) | |
tree | 83534cc83c316c10d9ed195f1c31bec869eaadf3 /app/scripts/lib/ComposableObservableStore.js | |
parent | 29dab1e9e00c1c1e6ad834026df51b2839d3171d (diff) | |
parent | 8974f933fc97a37f5cd8dcd510ff0e6dc21d6751 (diff) | |
download | tangerine-wallet-browser-3afe76bcba5eb1b84c748b13b61d1a22bed40bd3.tar tangerine-wallet-browser-3afe76bcba5eb1b84c748b13b61d1a22bed40bd3.tar.gz tangerine-wallet-browser-3afe76bcba5eb1b84c748b13b61d1a22bed40bd3.tar.bz2 tangerine-wallet-browser-3afe76bcba5eb1b84c748b13b61d1a22bed40bd3.tar.lz tangerine-wallet-browser-3afe76bcba5eb1b84c748b13b61d1a22bed40bd3.tar.xz tangerine-wallet-browser-3afe76bcba5eb1b84c748b13b61d1a22bed40bd3.tar.zst tangerine-wallet-browser-3afe76bcba5eb1b84c748b13b61d1a22bed40bd3.zip |
Merge pull request #3975 from MetaMask/i3947-composableStore
Add ComposableObservableStore for subscription management
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 |