Files: 32bfa7adad1fe9cf5b68bf33d66a08c36fab8de1 / proxy.js
987 bytesRaw
1 | var LazyWatcher = require('./lib/lazy-watcher') |
2 | var resolve = require('./resolve') |
3 | var isObservable = require('./is-observable') |
4 | |
5 | module.exports = Proxy |
6 | |
7 | function 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