M
M
Misty Hedgehog2016-08-09 15:50:48
JavaScript
Misty Hedgehog, 2016-08-09 15:50:48

Proxying nested object changes in JavaScript?

Good day, %username%!
So JavaScript. We have an object (with load/save methods) to store application settings (in localstorage), and this object looks like this:

var SettingsStorage = {
  data: {
    some_value1: null,
    child_object: {
      some_value2: true,
      some_value3: 1000
    },
    some_value4: null
  },
  load: function(callback) {
    // load this.data from localstorage
  },
  save: function(callback) {
    // save this.data to localstorage
  }
};

And there is a proxy object for accessing view settings data:
var Settings = new Proxy(SettingsStorage.data, {
  set: function(obj, prop, value) {
    var storage_data = SettingsStorage.data;
    if (obj === storage_data && prop === 'some_value1') {
      console.log('Да да! Мы поймали момент изменения SettingsStorage.data.some_value1!');
    }
    obj[prop] = value;
    return true;
  }
});

And now, when Settings.some_value1 changes, we change SettingsStorage.data.some_value1 and we can execute arbitrary code at the time of the change (for example, save the changes, which will save us from a forced call to SettingsStorage.save ()).
And everything would be fine, if it were not for the need to intercept the moment of changing SettingsStorage.data.child_object.some_value2 - this trick does not work with child objects. How to do it?
ps. This approach is necessary in order to change its behavior in general when changing any important application settings. In other words, you need to catch changes in the properties of the object, without writing a separate object with a cloud of getters / setters + rewriting the already created api. Browser - Google Chrome.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konstantin Gromov, 2016-08-09
@paramtamtam

https://jsfiddle.net/g1kebLbg Everything is very complicated. It took 2 hours and I'm still not sure that there are no bugs.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question