为什么在收集中使用模型的主干

时间:2013-10-27 17:54:08

标签: javascript backbone.js backbone-model backbone-collections

为什么在集合中使用模型,有人可以解释一下吗?

示例:

var model = Backbone.Model.extend({
  url: '/rest/article/'
});

var collection = Backbone.Collection.extend({
  url: '/rest/article',
  model: model
});

2 个答案:

答案 0 :(得分:1)

因此,无论何时向集合中添加项目,都可以将其实例化为该类型的模型。

答案 1 :(得分:1)

var model = Backbone.Model.extend({
  parse : function (response) {
    // you can modify model
    response.author || (response.author = 'Anonymous');
    return response;
  },
  getArticleTitle : function () {
    return this.get('author') + ' - ' + this.get('title');
  }
});

var collection = Backbone.Collection.extend({
  url: '/rest/article',
  model: model
});

// you can access model methods
collection.at(0).getArticleTitle();