HTML5 localStorage JSON改进 [英] HTML5 localStorage JSON improvement
问题描述
Storage.prototype.setObject = function(key, value) {
this.setItem(key, JSON.stringify(value));
}
Storage.prototype.getObject = function(key) {
var value = this.getItem(key);
return value && JSON.parse(value);
}
这是一个巧妙的解决方案。如何改进'点符号'的解决方案?
This is a cleverly solution. How to improve this solution to the 'dot notation'?
我的存储对象
var user = { "name":"testName", "surname":"testSurname" };
localStorage.setObject("user", user);
我的目的是通过这种方式获取名称内容
My purpose is to get name content by this way
var name = localStorage.user.name;
我不知道它是如何开发javascript原型的。
I don't know how it is developed javascript prototype.
推荐答案
由于你有一个setter,它可以让你对商店有足够的控制来创建你的行为。由于存储了键/值,我们可以在启动时查找上次的值,并透明地升级它们(如果需要)。使用setObject()和setItem()的一个好处是我们重新定义的属性不会妨碍重新设置新值。 v
Since you have a setter, that gives you enough control over the stores to create your behavior. Since key/values are stored, we can look for last time's values on boot, and upgrade them transparently (if needed). One nice thing about using setObject() and setItem() is that our re-defined properties don't get in the way of re-setting new values. v
我仍然认为这可能会导致与使用localStorage的其他应用程序发生冲突,并且它会将ƒ字符保留为特殊字符,但是如果使用setObject()方法每次保存对象时,以下效果都很好:
I still think this could cause conflicts with other apps that use localStorage, and it reserves the "ƒ" char as special, but if you use your setObject() method each time to save objects, the following works well:
(function() {
function makeDot(key, value){
Object.defineProperty(localStorage, key, {
configurable: true,
enumerable: true,
get: function() {
return typeof value==="string" && value.slice(0,1)==="ƒ" ?
JSON.parse(value.slice(1)) :
value;
}
});
}
Storage.prototype.setObject = function(key, value) {
this.setItem(key, "ƒ"+JSON.stringify(value));
makeDot(key, value);
}
// upgrade existing object stores:
Object.keys(localStorage).forEach(function(a){
var v=localStorage[a];
if(typeof v==="string" && v.slice(0,1)==="ƒ"){
makeDot(a, v);
}
});
}());
var user = {
"name": "testName",
"surname": "testSurname"
};
localStorage.setObject("user", user); //save object
alert( localStorage.user.surname ); // shows: "testSurname"
参见 http://jsfiddle.net/hrepekbb/ 踢轮胎
如果你想设置带点符号的对象,那么你需要使用观察者或者反映localStorage的代理,但这些选项都没有为黄金时段做好准备。
if you want to set objects with the dot notation, well then then you need to use an observer or maybe proxy reflecting localStorage, but neither of those options are quite ready for prime-time yet.
这篇关于HTML5 localStorage JSON改进的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!