Commit 6b2214914b0a2bdf4c9c1a0d139a2de5ebde31b2
add proxy-dict
Matt McKegg committed on 9/12/2016, 12:59:35 PMParent: b424e0dd69696f9db8b920d2b503320da01b5f98
Files changed
proxy-dict.js | added |
proxy-dict.js | ||
---|---|---|
@@ -1,0 +1,69 @@ | ||
1 | +var LazyWatcher = require('./lib/lazy-watcher') | |
2 | +var resolve = require('./resolve') | |
3 | +var isObservable = require('./is-observable') | |
4 | + | |
5 | +module.exports = ProxyDict | |
6 | + | |
7 | +function 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 | +} |
Built with git-ssb-web