As illustrated in a Stack Overflow thread, utilizing Proxy
objects is an effective method for monitoring changes in an object.
But what if you need to monitor changes in subobjects? In such cases, you will also have to proxy those subobjects.
I am currently working with code that automates this process - ensuring that any attempted property setting triggers the wrapping of the value in a proxy. This functionality allows us to take action whenever any value changes.
function createProxiedObject(objToProxy) {
return new Proxy(objToProxy, {
set: function (target, key, value) {
//proxy nested objects
if (value !== null && typeof value === 'object') {
value = createProxiedObject(value);
}
target[key.toString()] = value;
handleProxiedObjectChange();
});
While this approach works effectively, there is one scenario where it can cause issues:
function ensureObjectHasProperty(object, key, default) {
if (object[key] !== null) {
// some validation occurs here
return object[key];
} else {
return default;
}
}
...
proxiedObject = somethingThatCreatesAProxiedObject(someValue);
proxiedObject[someProperty] = ensureObjectHasProperty(proxiedObject, someProperty, defaultValue)
In this situation, the value under someProperty
(which is already proxied) may inadvertently get reassigned to the proxied object, resulting in double-wrapping. Consequently, the handleProxiedObjectChange
method may be triggered multiple times with each change in the object.
To prevent this issue, one solution could be to avoid assigning anything to the proxied object unless it's truly new. However, given that the problem has already occurred, there is a risk of it happening again in the future. How can I modify the set
function to prevent rewrapping objects that are already proxied? Alternatively, is there a more efficient way to monitor an object so that handleProxiedObjectChange
is invoked whenever the object or any of its subobjects undergo a change?