jds
jds

Reputation: 8279

Setting and getting models by CID in Backbone

I have this collection:

App.Collection.Pieces = Backbone.Collection.extend({
  model: App.Model.Piece,
  initialize: function() {
    this.add(
      // The `King` model extends the `Piece` model
      new App.Model.King({
        cid: 'wk',
        color: 'white'
      })
    );
  }
});

Then I have this code in a view:

this.white = new App.Collection.Pieces();
console.log(this.white.get('wk'));

I have two questions:

  1. Can I add a model B to a collection of A models, if B extends A?
  2. The console.log statement returns undefined. Any reason why the cid property is not being set?

Thanks.

Upvotes: 0

Views: 150

Answers (1)

cabe56
cabe56

Reputation: 404

  1. You can add any object or model to a collection. If its a plain JS object, the model defined for the collection will be instantiated. Annotated source

  2. According to Backbone's documentation the cid is automatically assigned to all models created. Looking at the annotated source it seems the cid is automatically generated - you cannot assign a custom cid to a model.

Upvotes: 1

Related Questions