mirror of
https://github.com/kremalicious/metamask-extension.git
synced 2024-12-23 09:52:26 +01:00
51 lines
1.1 KiB
JavaScript
51 lines
1.1 KiB
JavaScript
|
const Dnode = require('dnode')
|
||
|
const ObservableStore = require('./index')
|
||
|
const endOfStream = require('end-of-stream')
|
||
|
|
||
|
//
|
||
|
// HostStore
|
||
|
//
|
||
|
// plays host to many RemoteStores and sends its state over a stream
|
||
|
//
|
||
|
|
||
|
class HostStore extends ObservableStore {
|
||
|
|
||
|
constructor (initState, opts) {
|
||
|
super(initState)
|
||
|
this.opts = opts || {}
|
||
|
}
|
||
|
|
||
|
createStream () {
|
||
|
const self = this
|
||
|
// setup remotely exposed api
|
||
|
let remoteApi = {}
|
||
|
if (!self.opts.readOnly) {
|
||
|
remoteApi.put = (newState) => self.put(newState)
|
||
|
}
|
||
|
// listen for connection to remote
|
||
|
const dnode = Dnode(remoteApi)
|
||
|
dnode.on('remote', (remote) => {
|
||
|
// setup update subscription lifecycle
|
||
|
const updateHandler = (state) => remote.put(state)
|
||
|
self._onConnect(updateHandler)
|
||
|
endOfStream(dnode, () => self._onDisconnect(updateHandler))
|
||
|
})
|
||
|
return dnode
|
||
|
}
|
||
|
|
||
|
_onConnect (updateHandler) {
|
||
|
// subscribe to updates
|
||
|
this.subscribe(updateHandler)
|
||
|
// send state immediately
|
||
|
updateHandler(this.get())
|
||
|
}
|
||
|
|
||
|
_onDisconnect (updateHandler) {
|
||
|
// unsubscribe to updates
|
||
|
this.unsubscribe(updateHandler)
|
||
|
}
|
||
|
|
||
|
}
|
||
|
|
||
|
module.exports = HostStore
|