木偶的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耶每個方法都有其缺點。如果您無法控制模板,則應相應地設計視圖,而不一定採用解耦方法。 –