I'm trying to build a deep proxy to observe all the changes in an object in javascript. Here is what I got so far :
function GetDeepProxy(value, config, path = 'root')
{
var handler = function(config) {
return {
set: function(target, name, value) {
if(typeof config.beforeSet === 'function')
{
config.beforeSet(target, name, value, this.path);
}
target[name] = GetDeepProxyHelper(value, handler(config), this.path + '.' + name);
if(typeof config.afterSet === 'function')
{
config.afterSet(target, name, value, this.path);
}
return true;
}
}
};
var GetDeepProxyHelper = function(value, handler, path)
{
handler.path = path;
if(typeof value === 'object')
{
for(var prop in value)
{
if(typeof value[prop] === 'object')
{
value[prop] = GetDeepProxyHelper(value[prop], handler, path + '.' + prop);
}
}
return new Proxy(value, handler);
}
else
{
return value;
}
}
return GetDeepProxyHelper(value, handler(config), path);
}
You can then use it like that :
var myConfig = {
afterSet: function(target, name, value, path)
{
console.log('set :', path + '.' + name + ' = ', value);
},
beforeSet: function(target, name, value, path)
{
//console.log('setting :', path + '.' + name + ' = ', value);
}
}
var proxy = GetDeepProxy({}, myConfig, 'proxy');
proxy.test = [];
proxy.test.push('hi');
proxy.test[0] = 'abc';
proxy.test.push('def');
proxy.test = proxy.test.slice(1);
proxy.deep = {};
proxy.deep.abc = 'abc';
proxy.deep2 = { abc: { test: {} } };
proxy.deep2.abc.test.value = 'test';
console.log(proxy);
console.log(JSON.stringify(proxy));
Which print the following result
(index):160 set : root.test = []
(index):160 set : root.test.0 = hi
(index):160 set : root.test.length = 1
(index):160 set : root.test.0 = abc
(index):160 set : root.test.1 = def
(index):160 set : root.test.length = 2
(index):160 set : root.test = ["def"]
(index):160 set : root.deep = {}
(index):160 set : root.deep.abc = abc
(index):160 set : root.deep2 = {abc: Proxy}
(index):160 set : root.deep2.abc.test.value = test
(index):180 Proxy {test: Proxy, deep: Proxy, deep2: Proxy}
(index):181 {"test":["def"],"deep":{"abc":"abc"},"deep2":{"abc":{"test":{"value":"test"}}}}
Is there any modifications that I won't be able to observe using this approach and should I structure the code differently?