Files: dacc7137a972984d5f5adfe48e91c35b8056adb9 / proxy-collection.js
2326 bytesRaw
1 | var LazyWatcher = require('./lib/lazy-watcher') |
2 | var resolve = require('./resolve') |
3 | var isObservable = require('./is-observable') |
4 | |
5 | module.exports = ProxyCollection |
6 | |
7 | function ProxyCollection (source) { |
8 | var releases = [] |
9 | |
10 | var binder = LazyWatcher(update, listen, unlisten) |
11 | binder.value = resolve(source) |
12 | |
13 | var observable = function MutantProxyCollection (listener) { |
14 | if (!listener) { |
15 | return binder.getValue() |
16 | } |
17 | return binder.addListener(listener) |
18 | } |
19 | |
20 | observable.get = function (index) { |
21 | if (isObservable(source) && source.get) { |
22 | return source.get(index) |
23 | } else if (Array.isArray(resolve(source))) { |
24 | return resolve(source)[index] |
25 | } |
26 | } |
27 | |
28 | observable.getLength = function () { |
29 | if (isObservable(source) && source.getLength) { |
30 | return source.getLength() |
31 | } else if (Array.isArray(resolve(source))) { |
32 | return resolve(source).length |
33 | } |
34 | } |
35 | |
36 | observable.includes = function (value) { |
37 | if (isObservable(source) && source.includes) { |
38 | return source.includes(value) |
39 | } else if (Array.isArray(resolve(source))) { |
40 | return !!~resolve(source).indexOf(value) |
41 | } |
42 | } |
43 | |
44 | observable.indexOf = function (value) { |
45 | if (isObservable(source) && source.indexOf) { |
46 | return source.indexOf(value) |
47 | } else if (Array.isArray(resolve(source))) { |
48 | return resolve(source).indexOf(value) |
49 | } |
50 | } |
51 | |
52 | observable.forEach = function (fn, context) { |
53 | if (isObservable(source) && source.forEach) { |
54 | return source.forEach(fn, context) |
55 | } else if (Array.isArray(resolve(source))) { |
56 | return resolve(source).slice().forEach(fn, context) |
57 | } |
58 | } |
59 | |
60 | observable.find = function (fn) { |
61 | if (isObservable(source) && source.find) { |
62 | return source.find(fn) |
63 | } else if (Array.isArray(resolve(source))) { |
64 | return resolve(source).find(fn) |
65 | } |
66 | } |
67 | |
68 | observable.set = function (newSource) { |
69 | unlisten() |
70 | source = newSource |
71 | if (binder.live) { |
72 | listen() |
73 | } |
74 | binder.onUpdate() |
75 | } |
76 | |
77 | return observable |
78 | |
79 | // scoped |
80 | |
81 | function listen () { |
82 | if (isObservable(source)) { |
83 | releases.push( |
84 | source(binder.onUpdate) |
85 | ) |
86 | } |
87 | } |
88 | |
89 | function unlisten () { |
90 | while (releases.length) { |
91 | releases.pop()() |
92 | } |
93 | } |
94 | |
95 | function update () { |
96 | binder.value = resolve(source) || {} |
97 | return true |
98 | } |
99 | } |
100 |
Built with git-ssb-web