首页 文章

使用localStorage和sessionStorage作为元素树

提问于
浏览
2

在应用程序重构期间,我最近发现localStorage和sessionStorage是键值存储,所以问题:是使用localStorage,sessionStorage作为JSON的任何JavaScript实现,并保持通过浏览器调试工具轻松编辑它们的能力?

示例:我们为密钥应用程序创建了一些值,它具有设置,连接等子键,它们具有属性的子键 .

所以,像这样轻松地互动它们:

if (localStorage.application.connection.URI.slice(0, 5) === "https") { ... }

并且,如果我们需要销毁属性的分支并重新初始化它们:

localStorage.application.connection = undefined;

有什么办法吗?我知道,我可以使用

if (localStorage.getItem("application.connection.URI").slice(0, 5) === "https") { ... }

而且(回答这个问题How to remove localStorage data starting with a certain string?

for (key in localStorage) {
    if (key.substring(0,22) == 'application.connection') {
        localStorage.removeItem(key);
    }
}

但它有点难以阅读和使用 .

有什么建议?抱歉我的英语 .

1 回答

  • 0

    有点晚了但是你去了:大约一年前我实施了DotStorage作为一个hacky解决方案 .

    它既没有维护也没有经过全面测试,但它完成了这项工作 .
    ...我刚检查了回购:请注意你需要pako才能使用....

    不要将它用于大的东西,因为这是通过在代理中自动包装对象及其属性来实现的 - implementing deep change detection by trapping everything.

    Usage: 像任何其他Javascript对象一样,它只是持久性的:

    dotStorage.Hello = "World";
    // reload page
    console.assert(dotStorage.Hello == "World");
    

    你可以看看我的基于JSFiddle的测试文件here

    Example:

    var myObj = {"New": "object"};
    
    // save the object
    dotStorage.refTest = myObj;
    
    // get proxified instance
    myObj = dotStorage.refTest;
    
    // change nested properties
    myObj.New = {"nested": {"otherObject": [0, 1]}};
    console.log(JSON.stringify(dotStorage.refTest.New));
    
    // reload the page ------------------------------------------
    
    // change more nested properties
    myObj.New.nested = 2;
    
    // everything is still there
    console.log(JSON.stringify(dotStorage.refTest.New));
    

相关问题