Backbone.js 为集合创建主干视图

Backbone.js 为集合创建主干视图,backbone.js,Backbone.js,如何将主干视图绑定到集合而不是模型?我是否需要将集合包装在模型中 e、 g 如果我有一个主干模型客户机和一组这些所谓的客户机 Client = Backbone.Model.extend({ defaults: { Name: '' } }); Clients = Backbone.Collection.extend({ model: Client, url: 'Clients' }); 还有一个观点 var ClientListVie

如何将主干视图绑定到集合而不是模型?我是否需要将集合包装在模型中

e、 g

如果我有一个主干模型客户机和一组这些所谓的客户机

Client = Backbone.Model.extend({
    defaults: {
        Name: ''
    }
});

Clients = Backbone.Collection.extend({
    model: Client,
    url: 'Clients'
});
还有一个观点

    var ClientListView = Backbone.View.extend({
        template: _.template($("#clients-template").html()),
        el: $('#clientlist'),

        initialize: function() {
            _.bindAll(this, 'render');

            this.collection = new Clients();
        },

        render: function( event ){
            $(this.el).html(this.template({ this.collection.toJSON()));

            return this;
        }
    });
然后我无法访问下划线模板中的每个客户端元素。但是如果我像这样包装这个集合

$(this.el).html(this.template({ clients: this.collection.toJSON() }));

那我就可以了。这是正确的方法吗?我希望这是一个常见的场景,但我找不到任何示例,我是否走错了方向?

是的,您需要传递包装的集合

Addy Osmani在他的示例中使用了类似的方法-参见示例和相应的:

他认为:

$el.html( compiled_template( { results: collection.models } ) );
在模板中:

<% _.each( results, function( item, i ){ %>
   ...
<% }); %>

你可能想看看。

你需要一个
var=this?@dubilla No,backbone将代理下划线方法的上下文设置为
this
。为什么
this有下划线字符。\u donutViews=[]?@这只是JavaScript中表示私有变量的约定。由于JavaScript没有明确的方式来定义私有成员,所以这种约定在区分私有成员和公共成员时非常常见。在大多数情况下,第二种约定不是很理想吗?使用渲染中的所有视觉相关功能,而第一个功能没有?
var DonutCollectionView = Backbone.View.extend({
  initialize : function() {
    this._donutViews = [];
    this.collection.each(function(donut) {
      that._donutViews.push(new UpdatingDonutView({
        model : donut,
        tagName : 'li'
      }));
    });
  },

  render : function() {
    var that = this;
    $(this.el).empty();

    _(this._donutViews).each(function(dv) {
      $(that.el).append(dv.render().el);
    });
  }
});