如何将骨干视图绑定到集合而不是模型?我是否需要将该集合包装在模型中?
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() }));
然后我可以。这是正确的方法吗?我希望这是一个常见的场景,但我找不到任何关于它的例子,我是否采取了错误的方式?
答案 0 :(得分:13)
是的,您需要传递包装的集合。
Addy Osmani在他的Backbone Fundamentals示例中使用了类似的方法 - 请参阅示例this view和相应的template:
在视图中:
$el.html( compiled_template( { results: collection.models } ) );
在模板中:
<% _.each( results, function( item, i ){ %>
...
<% }); %>
另一种方法是创建一个视图,为集合中的每个模型创建单独的视图。以下是An Intro to Backbone.js: Part 3 – Binding a Collection to a View的示例:
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); }); } });
答案 1 :(得分:0)
您可能需要查看backbone collectionView。