木偶的CollectionView使每收集项目视图实例。因此,您可以完全控制该项目。
假设您想列出处理所有列表本身的单个视图的用户。这将是这个样子:
var UserList = Backbone.View.extend({
template: _.template($('#user-list-template').html()),
render: function(){
this.$el.html(this.template({ users: this.collection.toJSON() }));
return this;
}
});
而且模板
<script type="text/template" id="user-list-template">
<ul>
<% _.each(users, function(user) { %>
<li><%= user.email %></li>
<% }) %>
</ul>
</script>
这是超级简单,看起来好从那里。
但是,然后,您要为列表中的每个用户添加一个编辑按钮。上述方法开始出现真正的问题。您必须猜测哪个元素已被点击,或将用户标识放在模板中的data-id
属性中。所有这一切吸。
该CollectionView
让你轻松处理,一切都在其范围内的责任。
做一个项目视图:
var UserListItem = Marionette.View.extend({
template: _.template($('#user-list-item-template').html()),
events: {
'click @ui.edit': 'onEdit',
},
ui: {
edit: '.edit-btn'
},
onEdit: function(e) {
this.model.id; // the user model directly accessible
}
});
随着一个超级简单的模板。
<script type="text/template" id="user-list-item-template">
<li><%= user.email %> <button type="button" class="edit-btn">edit</button></li>
</script>
然后在您的列表视图中使用它。
var UserList = Marionette.CollectionView.extend({
tagName: 'ul',
childView: UserListItem
});
之后,添加功能到您的项目视图是很容易的。它甚至可以在不同的列表中重复使用,因为列表和项目是分离的。
谢谢埃米尔。我已经在使用第二种方法,绑定事件并获取模型非常简单。当包含外部模板文件时,有一些“但是”使用这些方法?谢谢。 – moreirapontocom
@moreirapontocom耶每个方法都有其缺点。如果您无法控制模板,则应相应地设计视图,而不一定采用解耦方法。 –