admin管理员组

文章数量:1435081

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.

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.

Share Improve this question asked Feb 24, 2012 at 3:27 wong2wong2 35.8k51 gold badges138 silver badges182 bronze badges 5
  • Are you okay with writing a property for each one? – Ry- Commented Feb 24, 2012 at 3:29
  • 1 That's not possible (well you could use ES5 getters and setters I suppose). I suggest to incorporate data encapsulation and use a method to set the properties, such as set(key, value) and handle the synchronisation inside that function. – Felix Kling Commented Feb 24, 2012 at 3:30
  • 2 Javascript setters and getters are your answer (but only for browsers that support them). – RobG Commented Feb 24, 2012 at 3:30
  • @minitech it's better not for I properly have other properties in the future – wong2 Commented Feb 24, 2012 at 3:37
  • According to http://robertnyman./javascript/javascript-getters-setters.html, getters and setters work in Chrome 5+. – RobG Commented Feb 24, 2012 at 3:43
Add a ment  | 

1 Answer 1

Reset to default 3

According to @RobG 's ment, 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./1897209

本文标签: javascriptHow to detect property value onchange event of an objectStack Overflow