如何使用Object.defineProperty通知json对象值更改?

时间:2012-05-16 15:11:38

标签: 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"

当我将价值设置为价格意味着我想要通知。怎么做?

1 个答案:

答案 0 :(得分:3)

对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"  

基本上我们删除现有属性,保存其值,然后使用我们想要的属性创建属性。