git ssb

1+

Matt McKegg / mutant



Tree: dacc7137a972984d5f5adfe48e91c35b8056adb9

Files: dacc7137a972984d5f5adfe48e91c35b8056adb9 / proxy-dict.js

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

Built with git-ssb-web