How to notify json object value change using Object.defineProperty?

I know how to notify a value change in an object using Object.defineProperty, but I want to know how to notify a change in the value of a json object?

more about this

when create a new instance for strore and set the price value, notifyPriceChange will call ..

function store(){
    var price
    Object.defineProperty(this, "price", 
    {
        get : function(){
            return price;
        },
        set : function(newValue){

            price = newValue;
            notifyPriceChange();
        },

        enumerable : true,
        configurable : true
    });
}

I want to do the same here.

var obj = jQuery.parseJSON( '{"price":"120"}' );
obj.price = "John"

when I set the value to the price value, I want to notify. how to do it?

+3
source share
1 answer

JSON reference does not affect the problem.

Your problem is that you have an object objwith an existing property price, and you would like to be able to set up a function call if this value is changed.

:

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"  

, , , , .

+3

All Articles