git ssb

1+

Matt McKegg / mutant



Tree: fd48051c9a0ccc1e5fd254db048758d8eff91383

Files: fd48051c9a0ccc1e5fd254db048758d8eff91383 / proxy-dict.js

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

Built with git-ssb-web