jds
jds

Reputation: 8259

How to configure and initialize a Backbone collection with models

I have this Backbone collection:

App.Collection.Pieces = Backbone.Collection.extend({
  model: App.Model.Piece,
  initialize: function(models, options) {
    this.color = options.color;
    king = new this.model({
      color: this.color
    });
    this.add(king);
    console.log(this.models[0]); // the `king` model is logged
    }
});

The initialize function seems to create and add the king model just fine. But in another file, I instantiate the collection and log the results:

this.white = new App.Collection.Pieces([], { color: 'white' });
console.log(this.white.models[0]); // `undefined` is logged

Here, it seems as if nothing is added. Am I missing something?

Upvotes: 0

Views: 967

Answers (1)

mu is too short
mu is too short

Reputation: 434665

The collection is doing exactly what you're telling it to: it is creating a collection without any models.

From the fine manual:

constructor / initialize new Backbone.Collection([models], [options])

When creating a Collection, you may choose to pass in the initial array of models.

The [models] notation means that models is optional but you're passing an array as the initial model set, an empty array but an array nonetheless. If you have a look at the source, things will be clearer:

var Collection = Backbone.Collection = function(models, options) {
  //...
  this.initialize.apply(this, arguments);
  if (models) this.reset(models, _.extend({silent: true}, options));
};

so you see that first the initialize method is called and then reset is called to apply the initial model set. An empty array is truthy so you end up doing a this.white.reset([]) to erase the king you added.

If you don't pass the optional models argument then things will work out better for you:

this.white = new App.Collection.Pieces(null, { color: 'white' });

Alternatively, if you always wanted a king, you could override reset on the collection to make sure the king is there.

Upvotes: 2

Related Questions