1
votes

I'm trying to persist a Backbone collection into the localstorage.

I'm using Backbone.localstorage to save the collection into JSON:

products.forEach(function (product) {
                localStorage.setItem(product.get("id"), JSON.stringify(product));

            });

And they're saved properly, with corresponding IDs.

is it possible to do something like this for the retrieval:

  products.localStorage = localStorage;
  products.fetch();

I can see in the debugger that products collection now has a localstorage property set to my localstorage and I can see stringified JSON objects, but only as a property, not actual objects in the collection. If it's possible does the Backbone.localstorage do the parsing of JSON into backbone models or not ?

How might I do this ? Thank you.

1

1 Answers

2
votes

Take a look at Backbone.localStorage. This is probably doing exactly what you are trying to develop from scratch.

If you just want a simple way to store your collection, I suggest doing it manually:

// Save
var jsonCollection = products.toJSON();
localStorage.setItem('key', jsonCollection);

// Load
products.reset(localStorage.getItem('key'));