Add listener.js
This commit is contained in:
parent
3421f340f7
commit
5cf868a904
1 changed files with 25 additions and 0 deletions
25
listener.js
Normal file
25
listener.js
Normal file
|
@ -0,0 +1,25 @@
|
|||
export const listener = (target={}) => {
|
||||
let callbacks = new Map()
|
||||
function listen(prop, callback) {
|
||||
if ("object" == typeof prop && "forEach" in prop)
|
||||
prop.forEach(prop => this.listen(prop, callback))
|
||||
else if (callback)
|
||||
callbacks.set(prop, callback)
|
||||
else
|
||||
callbacks.delete(prop)
|
||||
}
|
||||
let proxy = new Proxy(target, {
|
||||
set: (target, prop, value) => {
|
||||
if (callbacks.has("*")) callbacks.get("*")(value, prop)
|
||||
if (callbacks.has(prop)) callbacks.get(prop)(value, prop)
|
||||
return Reflect.set(target, prop, value)
|
||||
},
|
||||
get: (target, prop, value) => {
|
||||
if (prop == "listen")
|
||||
return listen
|
||||
else
|
||||
return Reflect.get(target, prop)
|
||||
}
|
||||
})
|
||||
return proxy
|
||||
}
|
Loading…
Reference in a new issue