为集合创建主干视图
如何将主干视图绑定到集合而不是模型?我需要将集合包装在模型中吗?
例如,
如果我有一个骨干模型客户端以及称为客户端的集合
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() }));
,那么我就可以。这是解决这个问题的正确方法吗?我希望这是一个常见的场景,但我找不到任何例子,我的处理方式是否错误?
How can I bind a backbone view to a collection rather than a model? Do I need to wrap the collection in a model?
e.g.
If I have a backbone model Client and a collection of these called Clients
Client = Backbone.Model.extend({
defaults: {
Name: ''
}
});
Clients = Backbone.Collection.extend({
model: Client,
url: 'Clients'
});
and a view
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;
}
});
then I can't access each client element in the underscore template. However if I wrap the collection like this
$(this.el).html(this.template({ clients: this.collection.toJSON() }));
then I can. Is this the correct way to go about this? I would expect this to be a common scenario but I can't find any examples on it, am I going about it the wrong way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,您需要传递包装后的集合。
Addy Osmani 在他的 Backbone Fundamentals 示例中使用了类似的方法 - 请参阅示例 这个视图和相应的模板:
在视图中:
在模板中:
另一种选择是使用一个视图,为集合中的每个模型创建单独的视图。以下是 Backbone.js 简介:第 3 部分 – 绑定 中的示例集合到视图:
Yes, you need to pass the wrapped collection.
Addy Osmani is using similar approach in his Backbone Fundamentals examples - see for example this view and corresponding template:
In the view:
In the template:
Another alternative is to have a view that will create separate view for each model in the collection. Here is an example from An Intro to Backbone.js: Part 3 – Binding a Collection to a View:
您可能想看看backbone collectionView。
You might want to take a look at backbone collectionView.