So this is an example I created to create an observable object.
Question is – why isn’t the variable ‘update’ actually updated?
Also if there is a reason I should not implement it like this? and a better strategy please advise?
window.dataSubscriber = new Proxy({
history: [],
update: ''
}, {
set: function (target, key, value) {
window.dataSubscriber.history.push(value);
return value;
}
});
window.dataSubscriber.update = 'John';
window.dataSubscriber.update = 'Smith';
console.log(window.dataSubscriber)
/*
output:
{
history: ['John', 'Smith'],
update: ''
}
*/
Other attempts that failed for me
- I tried doing window.dataSubscriber = new Proxy([], …) and when pushing to that, it never keeps the history, and overwrites the original array value
- I tried doing window.dataSubscriber.history.push() outside the set method, and that never triggers the set method.
>Solution :
If you override the set method, then it’s your responsibility to do the actual update.
So you just need target[key] = value;
eg.
window.dataSubscriber = new Proxy({
history: [],
update: ''
}, {
set: function (target, key, value) {
window.dataSubscriber.history.push(value);
target[key] = value;
return value;
}
});
window.dataSubscriber.update = 'John';
window.dataSubscriber.update = 'Smith';
console.log(window.dataSubscriber)
/*
output:
{
history: ['John', 'Smith'],
update: ''
}
*/