javascriptbackbone.jsbackbone.js-collections

Backbone Collection with multiple models?


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?


Solution

  • 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
    });