git ssb

1+

Matt McKegg / mutant



Tree: 073f2ca837054c3b04113dd573e1a9e8b0c6ed29

Files: 073f2ca837054c3b04113dd573e1a9e8b0c6ed29 / proxy.js

1050 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) {
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