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