I'm fairly new to getters and setters and am looking for a way to listen for changes in an object to store the data immediately, without calling a Save()
function everytime a value gets changed. This is how I do it right now:
var myObject = {
Data: {
enabled: true,
show: false
},
Save: function () {
//store myObject.Data to local storage
},
Load: function () {
//load data from local storage and assign it to myObject.Data
},
doSomething: function () {
myObject.Load();
if (myObject.Data.enabled) {
myObject.Data.show = true;
myObject.Save();
}
}
Now I would like to optimize this code so everytime a property in myObject.Data
is changed, myObject.Save()
is executed. The problem I'm experiencing is that it seems only possible to define a getter for a property that has just one value, but not for a property that is an object itself.
var myObj = {
_Data: {
a: 0,
b: 1,
c: 3
},
set Data (a) {
console.log(a);
}
};
myObj.Data.a = 2;
This obviously doesn't work since myObj.Data
is not an object and doesn't have the same properties as myObj._Data
.
Thanks in advance for any help.
You are likely interested in the Proxy object.
I used a very simple debounce function
callHandler
in order to avoid calling theonSet
method dozens of times during array modifications. Otherwise,[1, 2, 3].splice(0, 1)
would call the set handler once per item in the original array.