@hxss/recursive-proxy

1.0.3 • Public • Published

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 default return val.constructor.name === 'Object';(only basic Object can be used as sub target);
  • getObject() - used for return Proxy object when we dive in new object. Doesn't get any argument but as any other traps run in context of RecursiveProxy object 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 for Proxy.
  • this.path - array-path that contain name of every opened branch of original target.
  • this.p0 - zero-point Proxy that using only with original target.
  • this.proxy - recursive Proxy that using for access to any sub target. This is the proxy that by default return by getObject method.

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: ddd

console.log('val:', rp.a.b.custom);

outputs:

getObject: ["a"]
getObject: ["a", "b"]
get: custom
val: CustomObject {}

Readme

Keywords

Package Sidebar

Install

npm i @hxss/recursive-proxy

Weekly Downloads

0

Version

1.0.3

License

ISC

Unpacked Size

5.2 kB

Total Files

3

Last publish

Collaborators

  • hxss