1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-11-30 08:09:15 +01:00
metamask-extension/app/scripts/lib/ComposableObservableStore.js

56 lines
1.5 KiB
JavaScript
Raw Normal View History

import ObservableStore from 'obs-store'
/**
* An ObservableStore that can composes a flat
* structure of child stores based on configuration
*/
export default 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
*/
2020-11-03 00:41:28 +01:00
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
*/
2020-11-03 00:41:28 +01:00
updateStructure(config) {
this.config = config
this.removeAllListeners()
for (const key in config) {
if (Object.prototype.hasOwnProperty.call(config, key)) {
2020-07-21 23:10:45 +02:00
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
*/
2020-11-03 00:41:28 +01:00
getFlatState() {
let flatState = {}
for (const key in this.config) {
if (Object.prototype.hasOwnProperty.call(this.config, key)) {
2020-07-21 23:10:45 +02:00
const controller = this.config[key]
2020-11-03 00:41:28 +01:00
const state = controller.getState
? controller.getState()
: controller.state
2020-07-21 23:10:45 +02:00
flatState = { ...flatState, ...state }
}
}
return flatState
}
}