StackOverflow question : Notify on property change
How to notify the json object value change using Object.defineProperty?
HTML
In answer to StackOverflow question <a href=""http://stackoverflow.com/questions/10621466/how-to-notify-the-json-object-value-change-using-object-defineproperty/10622223#10622223>How to notify the json object value change using Object.defineProperty?</a><Br><BR>
JavaScript
function store(change) {
var self = this;
for (var p in self) { // for each property
if (self.hasOwnProperty(p) && (typeof self[p] === 'number' || // if its a number
('' + self[p]).match(/^\d+$/))) { // or string containing only digits
(function(prop) {
var cache = self[prop]; // save current value
delete self[prop]; // delete the property
Object.defineProperty(self, prop, { // add back in
get: function() {
return cache;
},
set: function(newValue) {
cache = change(self, prop, newValue);
},
enumerable: true,
configurable: true
});
})(p);
}
}
}
obj = {
"price": "120",
"name": "John",
"amount": 12
};
store.apply(obj, [function(o, p, nv) {
document.write('Property ' + p + ' changed from ' + o[p] + ' to ' + nv + '<br/>');
return nv;}]);
obj.price = 130;
obj.name = 'Paul';
obj.amount = 15;
document.write(JSON.stringify(obj));