1

I'm using Backbone.localStorage and have the following Collection:

var PlayersCollection = Backbone.Collection.extend({
   model: Player,
   localStorage: new Backbone.LocalStorage("players-backbone"),
});

and trying to set initial data by using:

var col = new PlayersCollection([
  {
    "model": "myapp.person",
    "pk": 1
  },
  {
    "model": "myapp.person",
    "pk": 2
  }
]);

But unfortunately I have no the items above in my collection:

col.localStorage.records // [] nothing

How could I initialize localStorage store based in initial collection data?

Erik
  • 14,060
  • 49
  • 132
  • 218

1 Answers1

2

Okay, so, the first thing that comes to mind is the fact that Backbone.LocalStorage only loads data through 'sync' requests. This means that even if there was existing data in localStorage, you'd need to call col.fetch() before that data would be set into the collection.

For your specific example, this solution would suffice. However, it has its own set of caveats which I'd be happy to address if you can expand upon your needs:

var PlayersCollection = Backbone.Collection.extend({
   localStorage: new Backbone.LocalStorage("players-backbone"),
   initialize: function(){
       //  NOTE: Models are NOT set on Collection in initialize. Defer until ready.
       _.defer(function(){
           if(!this.isEmpty()){
               this.invoke('save');
               this.fetch();
           }
       }.bind(this));
});

var col = new PlayersCollection([
  {
    "model": "myapp.person",
    "pk": 1
  },
  {
    "model": "myapp.person",
    "pk": 2
  }
]);

col.once('sync', function(){
    console.log('col:', col.localStorage.records);
});

Obviously, the major concerns here are:

  • Event-driven initialize which is unintuitive. This can be resolved by having a factory which is in charge of creating your PlayersCollection, or by providing the collection with another method which needs to be ran after initialize. All solutions are slightly ugly.

  • Modification of existing localStorage data. By telling the collection to save upon load you'll end up modifying whatever's already in localStorage. This can be somewhat resolved by checking for an empty collection. However, you may still have some unexpected results.

However, my main concern is why you need to pull from localStorage when your collection has already been given its models. Why not just access the models in col instead of interrogating its records?

Sean Anderson
  • 27,963
  • 30
  • 126
  • 237