git ssb

1+

Matt McKegg / mutant



Tree: 69500ffe4bd08cc562cd2f9b1f8e41ea76335686

Files: 69500ffe4bd08cc562cd2f9b1f8e41ea76335686 / proxy.js

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