wong2
wong2

Reputation: 35750

How to detect property value onchange event of an object?

I have this object:

var Settings = {  
    color: localStorage.color,  
    size : localStorage.size
};  

I'd like to automatically save the new values to localStorage once they are changed, that means I'd like to do something like this:

Settings.onchange = function(p){  
    localStorage[p] = this[p];
};  

Is it possible?

PS: only Chrome support needed.

Upvotes: 5

Views: 6130

Answers (1)

wong2
wong2

Reputation: 35750

According to @RobG 's comment, I wrote this function, and it works!

function onPropertyChange(o, callback){
    for(var p in o){
        if(o.hasOwnProperty(p)){
            var originalVal = o[p];
            Object.defineProperty(o, p, {
               get: function(){
                   return originalVal;
               },
               set: function(val){
                   callback.call(o, p, val);
                   return originalVal = val;
               }
            });
        }
    }
}  

// example:  

var Settings = {
    color: localStorage.color || "red",
    size : localStorage.size  || "12px"
};

onPropertyChange(Settings, function(p, val){
    localStorage[p] = val;
});  

gist here: https://gist.github.com/1897209

Upvotes: 3

Related Questions