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
1 Answer
Reset to default 3According 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
版权声明:本文标题:javascript - How to detect property value onchange event of an object? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745626679a2667016.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论