简体   繁体   English

使用localStorage和sessionStorage作为元素树

[英]Using localStorage and sessionStorage as tree of elements

During application refactoring I very lately found out about localStorage and sessionStorage are key-value storages, so question: is thee any JavaScript implementation for using localStorage, sessionStorage as JSON, and stay ability to easely edit them via browser debug tools? 在应用程序重构期间,我最近才发现有关localStorage和sessionStorage是键值存储,因此问题:您是否有任何JavaScript实现将localStorage,sessionStorage作为JSON使用并保持通过浏览器调试工具轻松编辑它们的能力?

Example: We create some value for key application, it have sub-keys like settings, connection, they have subkeys for properties. 示例:我们为密钥应用程序创建一些值,它具有子密钥,如设置,连接,它们具有属性的子密钥。

So, easy way to interact them like this: 因此,这样简单的交互方式:

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

And, if we need to destroy branch for properties and re-init them: 而且,如果我们需要销毁属性的分支并重新初始化它们:

localStorage.application.connection = undefined;

Any way to do this? 有什么办法吗? I know, I can use 我知道,我可以使用

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

And (thx to this answer How to remove localStorage data starting with a certain string? ) 并且(此答案的重点是如何从某个字符串开始删除localStorage数据?

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

But it is slightly hard to read and use. 但是,它有点难以阅读和使用。

Any suggestions? 有什么建议么? And sorry for my english. 对不起,我的英语。

A bit late but here you go: I implemented DotStorage as a hacky solution for this about a year ago. 有点晚了,但是您可以使用:大约一年前,我将DotStorage用作此解决方案中的一个有问题的解决方案。

It's neither maintained nor fully tested but it does the job. 它既没有维护也没有经过全面测试,但是可以完成工作。
...I just checked the repo: be aware that you need pako for this to work.... ...我刚刚检查了回购协议:请注意,您需要使用pako才能使其正常工作。...

Don't use it for big things though as this is realized by automatically wrapping objects and their properties in proxies - implementing deep change detection by trapping everything. 尽管不要将它用于大型事情,因为这是通过自动将对象及其属性包装在代理中来实现的 - 通过捕获所有内容来实现深度更改检测。

Usage: like any other Javascript object, it's just persistent: 用法:像其他任何Javascript对象一样,它是持久的:

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


You can take a look at my JSFiddle based test file here 您可以在这里查看我基于JSFiddle的测试文件

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));

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

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