Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Setting child value on javascript proxy never actually gets updated

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • 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: ''
}
*/
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading