简体   繁体   English

HTML5 localStorage JSON改进

[英]HTML5 localStorage JSON improvement

The following code from Mr. Guria's answer . 以下代码来自Guria先生的回答

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'? 如何改进“点符号”的解决方案

For instance 例如

My stored object 我存储的对象

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;

I don't know how it is developed javascript prototype. 我不知道它是如何开发javascript原型的。

Since you have a setter, that gives you enough control over the stores to create your behavior. 由于您有一个setter,因此可以对商店进行足够的控制来创建您的行为。 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. 使用setObject()和setItem()的一个好处是我们重新定义的属性不会妨碍重新设置新值。 v v

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: 我仍然认为这可能会导致与使用localStorage的其他应用程序发生冲突,并且它将“ƒ”字符保留为特殊字符,但如果每次使用setObject()方法保存对象,则以下方法效果很好:

(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"

see http://jsfiddle.net/hrepekbb/ to kick the tires 看到http://jsfiddle.net/hrepekbb/来踢轮胎

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. 如果你想用点符号设置对象,那么你需要使用一个观察者或者反映localStorage的代理,但这些选项都没有为黄金时段做好准备。

You can't. 你不能。 Stored values from localStorage are always JSON strings. localStorage中的存储值始终是JSON字符串。 localStorage.getObject("user").name is the best you can do. localStorage.getObject("user").name是你能做的最好的。

You could set up a property with an access descriptor to act aa "proxy" property. 您可以设置具有访问描述符的属性,以充当“代理”属性。 Such a proxy property map onto a stored value, but you would need to do that for every value you wanted to access. 这样的代理属性映射到存储的值,但您需要为要访问的每个值执行此操作。

Object.defineProperty(localStorage, "user", {
    get: function() { return localStorage.getObject("realUserKey"); },
    set: function(v) { localStorage.setObject("realUserKey", v); }
});

Here, the realUserKey value of localStorage is being set and persisted, but the value is transparently accessible from the user property. 这里,正在设置和保持localStoragerealUserKey值,但是可以从user属性透明地访问该值。 Note that this setup does not persist and needs to be re-declared each page load, just like the getObject and setObject functions are. 请注意,此设置不会持久存在,需要在每个页面加载时重新声明,就像getObjectsetObject函数一样。

To reiterate: there is no way to generalize this strategy to arbitrary key values (not until the ES6 standard comes out of development and sees deployment in browsers). 重申:没有办法将此策略概括为任意键值(直到ES6标准出现在开发中并且看到在浏览器中部署)。 You must declare each "proxy" property explicitly. 您必须明确声明每个“代理”属性。

http://rhaboo.org does things like this: http://rhaboo.org做这样的事情:

var store = Rhaboo.persistent('Some name, any name');
if (!store.user)
  store.write('user', { name:'John', surname:'Smith' } );
store.user.write('phone', '0123 456789');
store.user.write('visited', new Date());
console.log(store.user.name);

BTW, I wrote rhaboo. 顺便说一句,我写了rhaboo。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM