从本地存储还原主干.js集合



在 Backbone.js 中,我将一个集合数组保存到本地存储中,如下所示:

for (var thing of app.things) {
    localStorage.setItem('thing-' + thing.cid, JSON.stringify(thing.collection.toJSON()));
}

我可以确认这些存储在Chrome本地存储检查器中。

我正在尝试使用以下代码恢复它们:

var localStorageRef = localStorage.getItem('thing-' + thing.cid);
if (localStorageRef) {
    thing.collection = JSON.parse(localStorageRef);
}

这不会引发错误,但它确实意味着下次我尝试触发第一个代码(setItem(会发生以下错误:

Uncaught TypeError: stave.collection.toJSON is not a function

我的第二个代码块中的某些内容使第一个代码块不再工作。

你用一个简单的数组替换thing.collection。相反,请使用分析的数据重置集合的内容。

thing.collection.reset(JSON.parse(localStorageRef));

或者,如果thing.collection还不是集合,请创建一个新集合:

thing.collection = new Backbone.Collection(JSON.parse(localStorageRef));

最新更新