@hxss/recursive-proxy
v1.0.3
Published
This is like native ES6 Proxy but recursive. Native syntax. Native functional multiplied by recursiveness.
Readme
RecursiveProxy.js
This is like native ES6 Proxy but recursive. Native syntax. Native functional multiplied by recursiveness.
Unlike other similar projects this class using only 2 js Proxies for traverse over your object. No new Proxy every time you need to get regular field.
Usage
var proxy = new RecursiveProxy(object[, handler = {}]);
As with original Proxy you can override any of traps:
this.traps = [
'apply',
'construct',
'defineProperty',
'deleteProperty',
'enumerate',
'get',
'getOwnPropertyDescriptor',
'getPrototypeOf',
'has',
'isExtensible',
'ownKeys',
'preventExtensions',
'set',
'setPrototypeOf'
];...with native syntax, but as first argument this traps will receive current target instead of original, that you specify in constructor.
And 2 new methods used by RecursiveProxy getter:
isObject(val)- return true|false. Used for detect if this field object that we can use as new target or this is just value that we send in traditional getter. By defaultreturn val.constructor.name === 'Object';(only basic Object can be used as sub target);getObject()- used for returnProxyobject when we dive in new object. Doesn't get any argument but as any other traps run in context ofRecursiveProxyobject and has access to all its fields.
RecursiveProxy fields
Every trap-method specified in handler can use any of this fields:
this.target- original target. Object that you use in constructor.this.curTarget- current target. Sub object that now using as target forProxy.this.path- array-path that contain name of every opened branch of original target.this.p0- zero-pointProxythat using only with original target.this.proxy- recursiveProxythat using for access to any sub target. This is the proxy that by default return bygetObjectmethod.
Examples
const s = {
a: {
b: {
c: {
d: 'ddd',
},
custom: new CustomObject(),
},
z: 'zzz',
},
};
var rp = new RecursiveProxy(s, {
get: function(target, prop, receiver) {
console.log('get:', prop);
return Reflect.get(...arguments);
},
getObject: function() {
console.log('getObject:', this.path);
return this.proxy;
},
});
console.log('val:', rp.a.b.c.d);outputs:
getObject: ["a"]
getObject: ["a", "b"]
getObject: ["a", "b", "c"]
get: d
val: dddconsole.log('val:', rp.a.b.custom);outputs:
getObject: ["a"]
getObject: ["a", "b"]
get: custom
val: CustomObject {}