-
Notifications
You must be signed in to change notification settings - Fork 0
/
listener.js
49 lines (44 loc) · 1.34 KB
/
listener.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
/*
A somewhat refined Proxy generator that lets you selectively listen to changed
properties and react accordingly.
Example:
const l = listener()
l.listen("contract", contract => speaker.speak(contract))
l.contract = Sithis.getNewContract()
*/
const registry = new WeakMap()
const listener = (target={}) => {
const callbacks = new Map()
const methods = Object.create(null)
methods.listen = function(name, fn, {once=false}={}) {
const callback = once
? (...args) => { this.forget(name, callback); return fn(...args) }
: fn
const set = callbacks.get(name) ?? new Set()
callbacks.set(name, set)
set.add(callback)
return this
}
methods.forget = function(name, callback) {
if (callback) {
const set = callbacks.get(name)
if (set) return set.delete(callback)
} else {
return callbacks.delete(name)
}
}
const proxy = new Proxy(target, {
set: (target, prop, value) => {
if (callbacks.has(null)) callbacks.get(null).forEach(callback => callback(value, target[prop], prop))
if (callbacks.has(prop)) callbacks.get(prop).forEach(callback => callback(value, target[prop], prop))
return Reflect.set(target, prop, value)
},
get: (target, prop, _value) => prop in methods
? methods[prop]
: target[prop]
})
registry.set(proxy, target)
return proxy
}
listener.raw = proxy => registry.get(proxy)
export default listener