i am trying to make a Proxy trap for a nested object (kinda trying to implement vuex reactive).
kinda succeeded in setting trap following this post: How to use javascript proxy for nested objects
my code looks like this:
//inside function
const isProxy = Symbol("isProxy");
const handler: ProxyHandler<StateObj> = {
get: (target, name, receiver) => {
if (name === isProxy) return true;
const prop = Reflect.get(target, name);
if (typeof prop == undefined) return;
this.track(target, name); // track the component that "get" object.
if (!prop.isProxy && typeof prop == "object") {
return new Proxy(prop, handler);
}
return prop;
},
set: (target, name, value, receiver) => {
if (target[name] == value) return true;
this.trigger(target, name); //set the trigger for the "tracked" object
Reflect.set(target, name, value);
return true;
},
apply(target: StateObj, thisArg: any, argArray: any[]): any {
}
};
return new Proxy(state, handler);
please dont mind with the track and trigger funcs which are the reactive thing used in vues.
this code was successful for all kinds of changes to the original object. the trap worked quiet well.
but the problem is, when i try to use Array.prototype.unshift
or Array.prototype.splice
to an array inside the proxied object, it doesn't work.
I figured out the reason why the error occurs, which is that Array.prototype.unshift
or Array.prototype.splice
methods directly assigns [Get] slot results of the original indexes of the array to the [Set] call, so when the [Set] trap is activated, it assigns a proxied array not the original 'target' property of the object
You can find the Prototype method specification in the ECMAscript document
1. Let fromValue be ? Get(O, from).
2. Perform ? Set(O, to, fromValue, true).
so when i assign a plain object or value to the object, the trap works just fine, but when i assign an object or value i did 'get' from the object which activates the proxy [get] trap, it fails with this error:
TypeError: Cannot read properties of undefined(reading 'isProxy')
which i think means that the object is proxied (not sure).
could you please suggest on any ways i can trap the behavior of unshift, splice or direct assignments like state[i] = state[i+1]
?