Backbone 像 collection 一样对待模型

Backbone treat model like collection

因为Collections其实是一个模型,它有属性等等,就像这个例子

var Images = Backbone.Collection.extend({
  url: 'https://api.myjson.com/bins/4v2d8'
});

var View = Backbone.View.extend({
  el: $('.images'), 

  initialize: function(){
    this.listenTo(this.collection, 'sync', this.render, this); // what is this keyword as the last param here?
  },

  render: function(){

    this.collection.each(function(model){
      this.$el.append($('<p>'+model.get('name')+'</>' ));
    }, this);

  }
});

$(function(){

  var images = new View({ collection: new Images() });

  images.collection.fetch();

});

http://jsbin.com/gohedeguto/edit?html,js,output

但为什么这个不起作用?

http://jsbin.com/seyoyeqeku/edit?html,js,output

我用 Model 替换了 Collection 并传递给了视图。我得到了 this.model.each of undefined.

Since Collections is actually a model

没有。这是错误的假设。集合不是模型,这就是您的代码不起作用的原因。

模型没有 each 方法,您的代码抛出以下错误:

Uncaught TypeError: this.model.each is not a function(…)

并且不要遵循迭代模型属性并打印其名称的其他答案,这没有意义。因为模型应该代表一个实体,比如一个人。它只有一个 属性 包含名称,迭代模型属性以访问其中一个是没有意义的,您可以使用 get() 方法直接访问它的属性而无需迭代。

虽然 是对的,但他没有详细说明原因。

一个Backbone模型有很多函数来管理一个attributes hash,并且经常被一个id引用。

一个Backbone集合是一个Backbone模型实例数组。它有一些相似和许多不同的功能来管理其 models array property,这是存储模型实例的地方。

其中一些函数是 Underscore.js 函数的代理。

Model's Underscore methods

  • 反转
  • 选择
  • 省略
  • 连锁
  • 为空

Collection's Underscore methods

目前一共46个,见榜单


collection.each(iteratee, [context])

_.each(collection.models, iteratee, [context]) 的代理。

Backbone 的模型没有 each 函数,因为它没有实际意义,并且有更好的方法来遍历模型的属性。