git ssb

1+

Matt McKegg / mutant



Tree: 32bfa7adad1fe9cf5b68bf33d66a08c36fab8de1

Files: 32bfa7adad1fe9cf5b68bf33d66a08c36fab8de1 / proxy.js

987 bytesRaw
1var LazyWatcher = require('./lib/lazy-watcher')
2var resolve = require('./resolve')
3var isObservable = require('./is-observable')
4
5module.exports = Proxy
6
7function Proxy (source) {
8 var releases = []
9
10 var binder = LazyWatcher(update, listen, unlisten)
11 binder.value = resolve(source)
12
13 var observable = function MutantProxy (listener) {
14 if (!listener) {
15 return binder.getValue()
16 }
17 return binder.addListener(listener)
18 }
19
20 observable.get = function () {
21 return source
22 }
23
24 observable.set = function (newSource) {
25 unlisten()
26 source = newSource
27 if (binder.live) {
28 listen()
29 }
30 binder.onUpdate()
31 }
32
33 return observable
34
35 // scoped
36
37 function listen () {
38 if (isObservable(source)) {
39 releases.push(
40 source(binder.onUpdate)
41 )
42 }
43 }
44
45 function unlisten () {
46 while (releases.length) {
47 releases.pop()()
48 }
49 }
50
51 function update () {
52 binder.value = resolve(source) || {}
53 return true
54 }
55}
56

Built with git-ssb-web