我知道如何使用 Object.defineProperty 通知对象中的值更改,但我想知道如何通知 json 对象值更改?
更多关于这个
当为 strore 创建一个新实例并将值设置为 price 时,notifyPriceChange 将调用 ..
function store(){
var price
Object.defineProperty(this, "price",
{
get : function(){
return price;
},
set : function(newValue){
price = newValue;
notifyPriceChange();
},
enumerable : true,
configurable : true
});
}
我想在这里做同样的事情。
var obj = jQuery.parseJSON( '{"price":"120"}' );
obj.price = "John"
当我将值设置为 price 时,意味着我要通知。如何做到这一点?
最佳答案
对 JSON 的引用与问题无关。
您的问题是您有一个对象 obj
和一个现有属性 price
并且您希望能够在该值更改时建立对函数的调用。
您的存储过程可以进行如下调整:
function store () {
var price;
// if this.price exists, save its value and delete it
if (this.hasOwnProperty ('price')) {
price = this.price;
delete this.price;
}
// Now define the price property specifying the callback on change
Object.defineProperty (this, "price", {
get : function(){
return price;
},
set : function (newValue) {
price = newValue;
notifyPriceChange ();
},
enumerable : true,
configurable : true
});
}
// call as follows :
var obj = jQuery.parseJSON ('{"price":"120"}');
store.apply (obj); // establish new price property with callback on change
obj.price = "John"
本质上,我们删除现有属性,保存其值,然后创建具有我们想要的属性的属性。
关于javascript - 如何使用 Object.defineProperty 通知 json 对象值的变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10621466/