I am trying to detect changes in an array of objects using JavaScript proxies.
Problem: Any time there is a change in array like deletion or insertion, i want to get that deleted or inserted item.
Current Code
target = [{ id: 1, a: 'a' }, { id: 2, a: 'b' }];
proxy = new Proxy(target, {
get: function (target, property: string, receiver) {
if (property === 'pop') {
console.log('deleted object', target[target.length - 1]);
}
console.log('get', property);
// property is index in this case
return target[property];
},
set: function (target, property, value, receiver) {
console.log('set', property, 'to', value);
target[property] = value;
// you have to return true to accept the changes
return true;
}
});
Current Thoughts:
I did a little workaround to get the deleted item from array but it only works for pop()
method because it deletes the last item from array. But i need a way to get the changes even it is made using splice
method or push
or pop
.
Thanks.
[Update] Solution I Found:
https://github.com/ElliotNB/observable-slim I used this library to detect changes in array, i am able to detect changes on nested properties inside array too. This is exactly what i was looking for.
The reason i am using this library is because it's using proxies.