Files: bc685ac97855accf26bcdf7168da942ffcdccd1a / proxy-collection.js
2395 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, 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 MutantProxyCollection (listener) { |
18 | if (!listener) { |
19 | return binder.getValue() |
20 | } |
21 | return binder.addListener(listener) |
22 | } |
23 | |
24 | observable.get = function (index) { |
25 | if (isObservable(source) && source.get) { |
26 | return source.get(index) |
27 | } else if (Array.isArray(resolve(source))) { |
28 | return resolve(source)[index] |
29 | } |
30 | } |
31 | |
32 | observable.getLength = function () { |
33 | if (isObservable(source) && source.getLength) { |
34 | return source.getLength() |
35 | } else if (Array.isArray(resolve(source))) { |
36 | return resolve(source).length |
37 | } |
38 | } |
39 | |
40 | observable.includes = function (value) { |
41 | if (isObservable(source) && source.includes) { |
42 | return source.includes(value) |
43 | } else if (Array.isArray(resolve(source))) { |
44 | return !!~resolve(source).indexOf(value) |
45 | } |
46 | } |
47 | |
48 | observable.indexOf = function (value) { |
49 | if (isObservable(source) && source.indexOf) { |
50 | return source.indexOf(value) |
51 | } else if (Array.isArray(resolve(source))) { |
52 | return resolve(source).indexOf(value) |
53 | } |
54 | } |
55 | |
56 | observable.forEach = function (fn, context) { |
57 | if (isObservable(source) && source.forEach) { |
58 | return source.forEach(fn, context) |
59 | } else if (Array.isArray(resolve(source))) { |
60 | return resolve(source).slice().forEach(fn, context) |
61 | } |
62 | } |
63 | |
64 | observable.find = function (fn) { |
65 | if (isObservable(source) && source.find) { |
66 | return source.find(fn) |
67 | } else if (Array.isArray(resolve(source))) { |
68 | return resolve(source).find(fn) |
69 | } |
70 | } |
71 | |
72 | observable.set = function (newSource) { |
73 | unlisten() |
74 | source = newSource |
75 | if (binder.live) { |
76 | listen() |
77 | } |
78 | binder.onUpdate() |
79 | } |
80 | |
81 | return observable |
82 | |
83 | // scoped |
84 | |
85 | function listen () { |
86 | if (isObservable(source)) { |
87 | releases.push( |
88 | source(binder.onUpdate) |
89 | ) |
90 | } |
91 | } |
92 | |
93 | function unlisten () { |
94 | while (releases.length) { |
95 | releases.pop()() |
96 | } |
97 | } |
98 | |
99 | function update () { |
100 | binder.value = resolve(source) || {} |
101 | return true |
102 | } |
103 | } |
104 |
Built with git-ssb-web