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?


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

You could also do it the backbone way. Check out the docs backbone collection

Basically you would create different models adding a tie breaker attribute say "type" in this case.

var file = Backbone.Model.extend({
        defaults: {
            // will need to include a tie breaker attribute in both models
            type: 'file'
        }
    }),
    folder = Backbone.Model.extend({
        defaults: {
            // tie breaker
            type: 'folder'
        }
    });

var fs = Backbone.Collection.extend({
    model: function(model, options) {
        switch(model.type) {
            case 'file':
                return new file(model, options);
                break;
            case 'folder':
                return new folder(model, options);
                break;
        }
    }
});

// after that just add models to the collection as always
new fs([
    {type: 'file',name: 'file.txt'},
    {type: 'folder',name: 'Documents'}
]);

Backbone documention is not complete in this case. It will not work when used with merge:true option and idAttribute . In that case you need to:

var ModelFactory = function (attr, options) {
  switch (attr.type) {
    case 'file':
      return new file(attr, options);
    case 'folder':
      return new folder(attr, options);
  }
};
ModelFactory.prototype.idAttribute = '_id';

var fs = Backbone.Model.extend({
   model: ModelFactory
});
链接地址: http://www.djcxy.com/p/67142.html

上一篇: 使用backbone.js在模型中保存嵌套集合

下一篇: 骨干集合与多个模型?