js/listener.js

49 lines
1.3 KiB
JavaScript
Raw Normal View History

/*
A somewhat refined Proxy generator that lets you selectively listen to changed
properties and react accordingly.
Example:
const l = listener()
2022-07-01 07:05:58 +00:00
l.listen("contract", contract => speaker.speak(contract))
l.contract = Sithis.getNewContract()
*/
2023-03-06 09:54:20 +00:00
const registry = new WeakMap()
const listener = (target={}) => {
2022-03-16 15:45:48 +00:00
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
let set = callbacks.get(name) ?? new Set()
callbacks.set(name, set)
set.add(callback)
return this
2022-03-16 15:45:48 +00:00
}
methods.forget = function(name, callback) {
if (callback) {
const set = callbacks.get(name)
if (set) return set.delete(callback)
} else {
return callbacks.delete(name)
}
2021-06-23 14:04:33 +00:00
}
let proxy = new Proxy(target, {
set: (target, prop, value) => {
2022-03-16 15:45:48 +00:00
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))
2021-06-23 14:04:33 +00:00
return Reflect.set(target, prop, value)
},
2022-03-16 15:45:48 +00:00
get: (target, prop, value) => prop in methods
? methods[prop]
2022-02-15 14:50:20 +00:00
: target[prop]
2021-06-23 14:04:33 +00:00
})
2022-02-15 14:50:20 +00:00
registry.set(proxy, target)
2021-06-23 14:04:33 +00:00
return proxy
}
2021-11-23 15:30:11 +00:00
2022-02-15 14:50:20 +00:00
listener.raw = proxy => registry.get(proxy)
2021-11-23 15:30:11 +00:00
export default listener