渲染Backbone.js集合

Cim*_*imm 15 collections render backbone.js

我是一个Backbone.js n00b,并试图绕过它.我知道如何使用视图和内置的underscore.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"}]);
});
Run Code Online (Sandbox Code Playgroud)

它打破了视图中的模板属性行,但我不确定这是我需要查看的位置.我应该渲染一个集合,还是我完全忽略了这一点(也许集合只是将对象分组,我不应该把它看成可以渲染的列表)?

谢谢你的帮助......

dir*_*ira 32

问题是,当您定义ContinentsView时,模板会被评估并使用$('#continents-template')- 但DOM还没有准备好,所以它找不到模板.

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

ContinentsView = Backbone.View.extend({
  el: '#continents',
  initialize: function() {
     this.template = _.template($('#continents-template').html());
  }
  ...
Run Code Online (Sandbox Code Playgroud)

关于集合,是的,它们是分组对象,特别是模型集.

您应该创建代码,以便模型(和集合)不了解视图,只有视图知道模型.

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});
});
Run Code Online (Sandbox Code Playgroud)


Bra*_*ave 6

值得注意的是,在视图中渲染集合时,还有其他复杂性会迅速抬头.例如,在从集合中添加或删除模型时,通常需要重新呈现视图.实施您自己的解决方案并不是火箭科学,但它可能值得研究现有的解决方案,因为那里有相当多的经过试验和测试的解决方案.

Backbone.CollectionView是一个强大的集合视图类,可以处理选择模型以响应鼠标点击,基于拖放重新排序集合,过滤可见模型等.

在骨干网之上构建的几个流行框架也提供了简单的集合视图类,如Backbone.Marionette,ChaplinLayout Manager.

尽管Backbone本身不提供任何用于呈现集合的结构,但这是一个非常重要的问题,很多人对如何完成它有不同的看法.幸运的是,生态系统已经有很多不错的选择,这是一个普遍的需求.