javascript - 如何使用 Object.defineProperty 通知 json 对象值的变化?

标签 javascript

我知道如何使用 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/

相关文章:

Javascript:[] = 5,没有语法错误?为什么?

javascript - 如何从按钮增加 java 脚本函数中的全局变量?

javascript - CKeditor 显示 JS 范围

javascript - 将 cURL 转换为 JQuery.ajax 请求

javascript 删除元素

javascript - 如何在 Node + mysql Express 中集成 Angular 主题

javascript - 在 Javascript 中检查二维数组边界

javascript - 如何通过 jquery/JavaScript 使用 Google XML 建议

javascript - 稍后捕获 jquery ajax 错误

javascript - Appceletor Titanium createWindow() 无法打开新窗口,错误