问题描述
我想代理localStorage设置器和获取器来解析对象,并像我使用常规对象一样按分配将它们保存到存储中。
保存单个KV项时非常简单,但尝试更新存储中的嵌套对象时(对我来说)很复杂。
我遇到的问题是如何使用target参数在对象中获得正确的位置。 为了解决这个问题,我将代理对象原型化回localStorage,并在每次代理调用设置时对其进行解析。
它的工作原理与预期的一样,但看起来不像正确的方法。
任何建议都值得赞赏。
Storage.prototype.proxy = {}
Storage.prototype.getAll = function () {
data = {};
Object.keys(this).forEach(key => {
try {
data[key] = JSON.parse(this[key])
} catch {
data[key] = this[key]
}
});
this.proxy = data;
return this.proxy;
}
Storage.prototype.update = function () {
this.clear();
obj = this.proxy;
Object.keys(obj).forEach(key => {
this.setItem(key,JSON.stringify(obj[key]));
});
}
Storage.prototype.dynamic = new Proxy(localStorage.getAll(),handler = {
get(target,prop) {
if (prop == 'isProxy') return true;
if (typeof target[prop] == 'undefined') return;
if (!target[prop].isProxy && typeof target[prop] === 'object') {
target[prop] = new Proxy(target[prop],handler);
}
return Reflect.get(...arguments);
},set() {
Reflect.set(...arguments);
localStorage.update();
return true;
},deleteProperty(target,prop) {
if (prop in target) {
delete target[prop];
localStorage.update();
}
}
});
const storage = localStorage.dynamic;
storage.new = {}; //create new key in storage that hold an object
storage.new.one = 1; //create new object in and assign 1 to it
console.log(storage.new.one); // prints 1
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)