I'm trying to create an object that is basically both a Proxy
and an EventTarget
.
(我正在尝试创建一个基本上既是Proxy
又是EventTarget
。)
The goal is to be able to subscribe to any changes made to this object. (目的是能够订阅对此对象所做的任何更改。)
Here's how I define this object:
(这是我定义此对象的方式:)
const target = new EventTarget()
const state = new Proxy(target, {
set: (obj, key, value) => {
Reflect.set(obj, key, value)
obj.dispatchEvent(new CustomEvent('change', {detail: {key, value}}))
},
deleteProperty: (obj, key) => {
Reflect.deleteProperty(obj, key)
obj.dispatchEvent(new CustomEvent('change', {detail: {key, value: undefined}}))
}
})
At this point I'd like to be able to call state.addEventListener('change', console.log)
but this gives me an error:
(此时,我希望能够调用state.addEventListener('change', console.log)
但这给了我一个错误:)
Uncaught TypeError: Illegal invocation
(未捕获的TypeError:非法调用)
So here's what works:
(所以这是有效的:)
target.addEventListener('change', console.log)
state.foo = 'bar'
// logs the event
But as I said, I'd like to have one single unified object that can be both the target (can be listened to with addEventListener
) and the store of values (proxied object in charge of dispatching the events when modified).
(但是正如我所说,我希望有一个单一的统一对象,它既可以作为目标(可以使用addEventListener
监听)又可以作为值的存储(代理对象,修改后用于调度事件)。)
So far, this method only works if you carry around both target
and state
... (到目前为止,如果你随身携带两个这种方法只适用target
和state
...)
Any idea why I can't call addEventListener
by going through the Proxy
?
(知道为什么我无法通过Proxy
调用addEventListener
吗?)
Technically, calling state.addEventListener()
goes through the get
prototype method, so I tried defining get: Reflect.get
in the proxy handler but it adds nothing... (Even though it was indeed reached because I tried adding a console.log
there too)
(从技术上讲,调用state.addEventListener()
会通过get
原型方法进行,因此我尝试在代理处理程序中定义get: Reflect.get
,但未添加任何内容...(即使确实达到了,因为我尝试添加console.log
那里))
So why can't I call addEventListener
through the proxy but it works fine directly on the target
object?
(那么,为什么不能通过代理调用addEventListener
,但是直接在target
对象上可以正常工作呢?)
ask by Sheraff translate from so