As others have noted, you can use the [Proxy][6] object to monitor (and intercept) changes made to an object. Here's a basic example:
var targetObj = {};
var targetProxy = new Proxy(targetObj, {
set: function (target, key, value) {
console.log(`${key} set to ${value}`);
target[key] = value;
return true;
}
});
targetProxy.hello_world = "test"; // console: 'hello_world set to test'
**However, what OP is trying to do is be notified of any mutation on a broader state object.** To do that, and use `Proxy`, you need an observer that will instrument the entire object graph. TJCrowder correctly noted that doing so is a non-trivial effort. You'll need to use a specialized library such as **[Observable Slim][8]** (which I have authored). This library does use `Proxy` under the hood, but handles all the complexity of performantly instrumenting the full object graph.
It works like this:
var test = {testing:{}};
var p = ObservableSlim.create(test, true, function(changes) {
console.log(JSON.stringify(changes));
});
p.testing.blah = 42; // console: [{"type":"add","target":{"blah":42},"property":"blah","newValue":42,"currentPath":"testing.blah",jsonPointer:"/testing/blah","proxy":{"blah":42}}]
[6]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
[8]: https://github.com/ElliotNB/observable-slim
You can use the [Proxy][6] object to monitor (and intercept) changes made to an object. It is purpose built for what the OP is trying to do. Here's a basic example:
var targetObj = {};
var targetProxy = new Proxy(targetObj, {
set: function (target, key, value) {
console.log(`${key} set to ${value}`);
target[key] = value;
return true;
}
});
targetProxy.hello_world = "test"; // console: 'hello_world set to test'
However, if you need to observe changes made to a **nested object**, then you need to use a specialized library such as **[Observable Slim][8]** (which I have authored).
It works like this:
var test = {testing:{}};
var p = ObservableSlim.create(test, true, function(changes) {
console.log(JSON.stringify(changes));
});
p.testing.blah = 42; // console: [{"type":"add","target":{"blah":42},"property":"blah","newValue":42,"currentPath":"testing.blah",jsonPointer:"/testing/blah","proxy":{"blah":42}}]
[6]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
[8]: https://github.com/ElliotNB/observable-slim