Add support for repeated callbacks to listener

It is now possible to attach several callbacks to the same prop on a
single listener object.
This commit is contained in:
Talia 2021-09-13 19:21:00 +02:00
parent 7a061b10d5
commit a303a83ad7
No known key found for this signature in database
GPG Key ID: AD727AD22802D0D6
1 changed files with 11 additions and 7 deletions

View File

@ -8,20 +8,24 @@ Example:
l.contract = new Contract() l.contract = new Contract()
*/ */
export const listener = (target={}) => { export default (target={}) => {
let callbacks = new Map() let callbacks = new Map()
function listen(prop, callback) { function listen(prop, callback) {
if ("object" == typeof prop && "forEach" in prop) if ("object" == typeof prop && "forEach" in prop) {
prop.forEach(prop => this.listen(prop, callback)) prop.forEach(prop => this.listen(prop, callback))
else if (callback) } else if (callback) {
callbacks.set(prop, callback) let list = callbacks.get(prop)
else if (!list) callbacks.set(prop, list=[])
list.push(callback)
} else {
callbacks.delete(prop) callbacks.delete(prop)
} }
}
let proxy = new Proxy(target, { let proxy = new Proxy(target, {
set: (target, prop, value) => { set: (target, prop, value) => {
if (callbacks.has("*")) callbacks.get("*")(value, prop) console.log(callbacks)
if (callbacks.has(prop)) callbacks.get(prop)(value, prop) if (callbacks.has("*")) callbacks.get("*").forEach(callback => callback(value, prop))
if (callbacks.has(prop)) callbacks.get(prop).forEach(callback => callback(value, prop))
return Reflect.set(target, prop, value) return Reflect.set(target, prop, value)
}, },
get: (target, prop, value) => { get: (target, prop, value) => {