Collections 呈现Backbone.js集合

Collections 呈现Backbone.js集合,collections,backbone.js,render,Collections,Backbone.js,Render,我是一个Backbone.js n00b,并试图让我的头脑绕过它。我知道如何使用视图和内置的underline.js模板引擎渲染模型。现在我正在尝试渲染一个集合,这就是我遇到的问题。这里没有服务器,所以我不会远程获取任何东西,只是一个带有JavaScript的简单HTML页面 ContinentModel = Backbone.Model.extend({}); ContinentsCollection = Backbone.Collection.extend({ model: Conti

我是一个Backbone.js n00b,并试图让我的头脑绕过它。我知道如何使用视图和内置的underline.js模板引擎渲染模型。现在我正在尝试渲染一个集合,这就是我遇到的问题。这里没有服务器,所以我不会远程获取任何东西,只是一个带有JavaScript的简单HTML页面

ContinentModel = Backbone.Model.extend({});

ContinentsCollection = Backbone.Collection.extend({
  model: ContinentModel,

  initialize: function () {
    this.continentsView = new ContinentsView;
    this.bind("reset", this.continentsView.render);
  }
});

ContinentsView = Backbone.View.extend({
  el: '#continents',
  template: _.template($('#continents-template').html()),

  render: function() {
    var renderedContent = this.template(this.collection.toJSON());
    $(this.el).html(renderedContent);
    return this;
  }
});

$(function() {
  var continentsCollection = new ContinentsCollection();
  continentsCollection.reset([{name: "Asia"}, {name: "Africa"}]);
});
它在视图中的模板属性行中断,但我不确定这是我需要查看的地方。我是应该渲染一个集合,还是完全忽略了这一点(也许集合只是对对象进行分组,我不应该将其视为可以渲染的列表)


感谢您的帮助…

问题是,当您定义大陆视图时,模板将被评估,并且它使用
$(“#大陆模板”)
-但是DOM尚未准备好,因此它找不到模板

要解决此问题,只需在initialize函数中移动模板分配:

ContinentsView = Backbone.View.extend({
  el: '#continents',
  initialize: function() {
     this.template = _.template($('#continents-template').html());
  }
  ...
关于集合,是的,它们是分组对象,特别是模型集

您应该编写代码,使模型(和集合)不知道视图,只有视图知道模型

ContinentModel = Backbone.Model.extend({});

ContinentsCollection = Backbone.Collection.extend({
  model: ContinentModel,
  // no reference to any view here    
});

ContinentsView = Backbone.View.extend({
  el: '#continents',

  initialize: function() {
    this.template = _.template($('#continents-template').html());
    // in the view, listen for events on the model / collection
    this.collection.bind("reset", this.render, this);
  },

  render: function() {
    var renderedContent = this.template(this.collection.toJSON());
    $(this.el).html(renderedContent);
    return this;
  }
});

$(function() {
  var continentsCollection = new ContinentsCollection();
  continentsCollection.reset([{name: "Asia"}, {name: "Africa"}]);
  // initialize the view and pass the collection
  var continentsView = new ContinentsView({collection: continentsCollection});
});

还值得注意的是,在视图中渲染集合时,还存在一些额外的复杂性,这些复杂性会很快让他们感到头疼。例如,在集合中添加或删除模型时,通常需要重新渲染视图。实现您自己的解决方案并不是一门火箭科学,但它可能值得研究现有的解决方案,因为有很多经过尝试和测试的解决方案

是一个健壮的集合视图类,用于处理响应鼠标单击选择模型、基于拖放对集合重新排序、过滤可见模型等

构建在主干之上的几个流行框架还提供了简单的集合视图类,如、和


尽管主干本身不提供任何用于呈现集合的结构,但这是一个非常重要的问题,许多人对此有不同的看法。幸运的是,这是一个普遍的需求,生态系统中已经有很多好的选择。

谢谢迪拉!模板现在可以工作了,而模型不应该知道视图的提示确实有帮助。仍然,
重置
似乎不会触发视图渲染功能。有什么想法吗?抱歉,我明白了,我必须把你例子中的最后两行改成非课程。在重置集合之前,我必须初始化大陆视图。谢谢@dira+1非常感谢您指出模型/集合不应该引用视图(至少是直接引用)。我的眼睛流了一会儿血