-
Notifications
You must be signed in to change notification settings - Fork 11
/
proxy-dict.js
80 lines (66 loc) · 1.62 KB
/
proxy-dict.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
var LazyWatcher = require('./lib/lazy-watcher')
var resolve = require('./resolve')
var isObservable = require('./is-observable')
module.exports = ProxyDict
function ProxyDict (source, opts) {
var releases = []
var binder = LazyWatcher(update, listen, unlisten)
binder.value = resolve(source)
if (opts && opts.nextTick) binder.nextTick = true
if (opts && opts.idle) binder.idle = true
var observable = function MutantProxyDict (listener) {
if (!listener) {
return binder.getValue()
}
return binder.addListener(listener)
}
observable.get = function (key) {
if (isObservable(source) && source.get) {
return source.get(key)
} else if (resolve(source)) {
return resolve(source)[key]
}
}
observable.keys = function () {
if (isObservable(source) && source.keys) {
return resolve(source.keys)
} else if (resolve(source)) {
return Object.keys(resolve(source))
} else {
return []
}
}
observable.has = function (key) {
if (isObservable(source) && source.has) {
return source.has(key)
} else if (resolve(source)) {
return key in resolve(source)
}
}
observable.set = function (newSource) {
unlisten()
source = newSource
if (binder.live) {
listen()
}
binder.onUpdate()
}
return observable
// scoped
function listen () {
if (isObservable(source)) {
releases.push(
source(binder.onUpdate)
)
}
}
function unlisten () {
while (releases.length) {
releases.pop()()
}
}
function update () {
binder.value = resolve(source) || {}
return true
}
}