In Backbone.js, I am saving an array of collections to localstorage like so:
for (var thing of app.things) {
localStorage.setItem('thing-' + thing.cid, JSON.stringify(thing.collection.toJSON()));
}
I can confirm these are being stored in the Chrome localstorage inspector.
I am trying to restore them with this code:
var localStorageRef = localStorage.getItem('thing-' + thing.cid);
if (localStorageRef) {
thing.collection = JSON.parse(localStorageRef);
}
This doesn't throw an error, but it does mean that the next time I try to trigger the first code (to setItem
) the following error occurs:
Uncaught TypeError: stave.collection.toJSON is not a function
Something in my second chunk of code is making the first chunk not work any longer.
You're replacing thing.collection
with a simple array. Instead, reset the content of the collection with the parsed data.
thing.collection.reset(JSON.parse(localStorageRef));
Or if thing.collection
is not a collection already, create a new one:
thing.collection = new Backbone.Collection(JSON.parse(localStorageRef));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.