2021-06-23 14:21:33 +00:00
|
|
|
/*
|
|
|
|
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.handle(contract))
|
|
|
|
l.contract = new Contract()
|
|
|
|
*/
|
|
|
|
|
2021-09-13 17:21:00 +00:00
|
|
|
export default (target={}) => {
|
2021-06-23 14:04:33 +00:00
|
|
|
let callbacks = new Map()
|
|
|
|
function listen(prop, callback) {
|
2021-09-13 17:21:00 +00:00
|
|
|
if ("object" == typeof prop && "forEach" in prop) {
|
2021-06-23 14:04:33 +00:00
|
|
|
prop.forEach(prop => this.listen(prop, callback))
|
2021-09-13 17:21:00 +00:00
|
|
|
} else if (callback) {
|
|
|
|
let list = callbacks.get(prop)
|
|
|
|
if (!list) callbacks.set(prop, list=[])
|
|
|
|
list.push(callback)
|
|
|
|
} else {
|
2021-06-23 14:04:33 +00:00
|
|
|
callbacks.delete(prop)
|
2021-09-13 17:21:00 +00:00
|
|
|
}
|
2021-06-23 14:04:33 +00:00
|
|
|
}
|
|
|
|
let proxy = new Proxy(target, {
|
|
|
|
set: (target, prop, value) => {
|
2021-09-13 17:21:00 +00:00
|
|
|
console.log(callbacks)
|
2021-10-19 16:08:22 +00:00
|
|
|
if (callbacks.has("*")) callbacks.get("*").forEach(callback => callback(value, prop, target[prop]))
|
|
|
|
if (callbacks.has(prop)) callbacks.get(prop).forEach(callback => callback(value, prop, target[prop]))
|
2021-06-23 14:04:33 +00:00
|
|
|
return Reflect.set(target, prop, value)
|
|
|
|
},
|
|
|
|
get: (target, prop, value) => {
|
|
|
|
if (prop == "listen")
|
|
|
|
return listen
|
|
|
|
else
|
|
|
|
return Reflect.get(target, prop)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
return proxy
|
|
|
|
}
|