Proxies don't really replace Object.observe (do they?)

325 views Asked by At

Javascript proxies are supposed to be the "more general" replacement for Object.observe, but one nice thing about Object.observe was that it let you monitor unintended changes. It could be used as a convenience method for debugging legacy code, for example. Proxies don't seem to function the same way; they only intercept interactions that happen through the proxy. Am I missing something?

1

There are 1 answers

0
Flavien Volken On

5 years later, the answer is no, they don't. Unfortunately, a proxy will only track the access to the proxy itself which is quite useless when you need to "spy" an existing object.

You could still try to create a proxy from an existing object and then replace that existing object with the proxy you just created from, but this is risky as there no warranty you will be replacing it everywhere.

Note: if I really need to observe the properties of an object i.e. to know when they changed, I'm using this helper. This is not plain JS as it make use of rxjs, but it works pretty well.

usage (typescript):

const obj: {key: string} = {key: "value"};
observeProperty$(obj, 'key').subscribe((nextValue)=>console.log(nextValue));

obj.key = "anotherValue"

// console output: "anotherValue"