[英]Restore Backbone.js collection from localstorage
在Backbone.js中,我將一組數組保存到localstorage中,如下所示:
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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.