aboutsummaryrefslogtreecommitdiffstats
path: root/app/scripts/lib/observable/host.js
blob: d1b110503588e88ca543cefeaf9fd48cf1be6048 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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