HTML5 localStorage JSON improvement

2019-05-10 21:23发布

问题:

The following code from Mr. Guria's answer.

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.

回答1:

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

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"

see http://jsfiddle.net/hrepekbb/ to kick the tires

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.



回答2:

You can't. Stored values from localStorage are always JSON strings. localStorage.getObject("user").name is the best you can do.

You could set up a property with an access descriptor to act a a "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. Note that this setup does not persist and needs to be re-declared each page load, just like the getObject and setObject functions are.

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). You must declare each "proxy" property explicitly.



回答3:

http://rhaboo.org does things like this:

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.