Backbone Collection with multiple models?

user1031947 picture user1031947 · Jan 10, 2013 · Viewed 11.1k times · Source

I'm learning Backbone.

I want to create a list that can contain different models, with different attributes.

For example, listing folder contents, which could include models of type file and models of type folder, in any order.

file : {
  title : "",
  date : "",
  type : "",
  yaddayadda : ""
}

folder : {
  title : "",
  date : "",
  haminahamina : ""
}

What is the proper way to represent this in Backbone? Is it possible to have a single Collection with multiple models?

Answer

Lukas picture Lukas · Jan 10, 2013

Create a base model that your other models inherit from:

var DataModel = Backbone.Model.extend({
    // Whatever you want in here
});

var FileModel = DataModel.extend({
    // Whatever you want in here
});

var FolderModel = DataModel.extend({
    // Whatever you want in here
});

And make the model type of the collection be that same base model:

var DataCollection = Backbone.Collection.extend({
    model: DataModel
});