Files: 099e49713653c62ab39055b073d7b9d37da7d803 / proxy-dict.js
1625 bytesRaw
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, opts) { |
8 | var releases = [] |
9 | |
10 | var binder = LazyWatcher(update, listen, unlisten) |
11 | binder.value = resolve(source) |
12 | |
13 | if (opts && opts.nextTick) { |
14 | binder.nextTick = true |
15 | } |
16 | |
17 | var observable = function MutantProxyDict (listener) { |
18 | if (!listener) { |
19 | return binder.getValue() |
20 | } |
21 | return binder.addListener(listener) |
22 | } |
23 | |
24 | observable.get = function (key) { |
25 | if (isObservable(source) && source.get) { |
26 | return source.get(key) |
27 | } else if (resolve(source)) { |
28 | return resolve(source)[key] |
29 | } |
30 | } |
31 | |
32 | observable.keys = function () { |
33 | if (isObservable(source) && source.keys) { |
34 | return resolve(source.keys) |
35 | } else if (resolve(source)) { |
36 | return Object.keys(resolve(source)) |
37 | } else { |
38 | return [] |
39 | } |
40 | } |
41 | |
42 | observable.has = function (key) { |
43 | if (isObservable(source) && source.has) { |
44 | return source.has(key) |
45 | } else if (resolve(source)) { |
46 | return key in resolve(source) |
47 | } |
48 | } |
49 | |
50 | observable.set = function (newSource) { |
51 | unlisten() |
52 | source = newSource |
53 | if (binder.live) { |
54 | listen() |
55 | } |
56 | binder.onUpdate() |
57 | } |
58 | |
59 | return observable |
60 | |
61 | // scoped |
62 | |
63 | function listen () { |
64 | if (isObservable(source)) { |
65 | releases.push( |
66 | source(binder.onUpdate) |
67 | ) |
68 | } |
69 | } |
70 | |
71 | function unlisten () { |
72 | while (releases.length) { |
73 | releases.pop()() |
74 | } |
75 | } |
76 | |
77 | function update () { |
78 | binder.value = resolve(source) || {} |
79 | return true |
80 | } |
81 | } |
82 |
Built with git-ssb-web