Files: 89e85f9009db15cde0d4a19d0f6fd5167a25d808 / proxy.js
1084 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, 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 MutantProxy (listener) { |
17 | if (!listener) { |
18 | return binder.getValue() |
19 | } |
20 | return binder.addListener(listener) |
21 | } |
22 | |
23 | observable.get = function () { |
24 | return source |
25 | } |
26 | |
27 | observable.set = function (newSource) { |
28 | unlisten() |
29 | source = newSource |
30 | if (binder.live) { |
31 | listen() |
32 | } |
33 | binder.onUpdate() |
34 | } |
35 | |
36 | return observable |
37 | |
38 | // scoped |
39 | |
40 | function listen () { |
41 | if (isObservable(source)) { |
42 | releases.push( |
43 | source(binder.onUpdate) |
44 | ) |
45 | } |
46 | } |
47 | |
48 | function unlisten () { |
49 | while (releases.length) { |
50 | releases.pop()() |
51 | } |
52 | } |
53 | |
54 | function update () { |
55 | binder.value = resolve(source) |
56 | return true |
57 | } |
58 | } |
59 |
Built with git-ssb-web