如何检测对象的onchange事件的属性值?

时间:2012-02-24 03:27:11

标签: javascript

我有这个对象:

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

我希望在更改后自动将新值保存到localStorage,这意味着我想要执行以下操作:

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

有可能吗?

PS:只需要Chrome支持。

1 个答案:

答案 0 :(得分:2)

根据@RobG的评论,我写了这个函数,它有效!

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;
});  

请点击此处:https://gist.github.com/1897209