这是我的JS代码
var mainApp = new Backbone.Marionette.Application();
mainApp.addRegions({
mainRegion: "#main-region"
});
var UserModel = Backbone.Model.extend();
var UserView = Backbone.Marionette.ItemView.extend({
tagName: 'div',
className: 'user-item',
template: '#user-item-tpl'
});
var UserCollection = Backbone.Collection.extend({
model: UserModel,
sortKey: 'id',
comparator: function(item1, item2){
item1 = item1.get(this.sortKey);
item2 = item2.get(this.sortKey);
return item1 > item2 ? 1 : (item1 < item2 ? -1 : 0);
},
sortByID: function(){
this.sort();
}
});
var UserListView = Backbone.Marionette.CompositeView.extend({
className: 'user-view',
tagName: 'div',
itemView: UserView,
itemViewContainer: '.user-list',
events: {
'click .btn' : 'doSort'
},
collection: new UserCollection([
{id: 3, name: 'Peter'},
{id: 1, name: 'Tom'},
{id: 2, name: 'Mary'}
]),
initialize: function(){
},
onShow: function(){
},
appendHtml: function(collectionView, itemView, index){
$(this.itemViewContainer).append(itemView.el);
},
render: function(){
this.template = _.template($('#user-view-tpl').html());
this.$el.html(this.template());
return this;
},
doSort: function(){
this.collection.sortByID();
this.collection.trigger('reset');
console.log(this.collection.toJSON());
}
});
mainApp.mainRegion.show(new UserListView());
这是html
<div id="main-region"></div>
<script id="user-view-tpl" type="text/template">
<div class="user-list"></div>
<a class="btn">SORT</a>
</script>
<script id="user-item-tpl" type="text/template">
<%= id %> | <%= name %>
</script>
每当我通过单击“SORT”按钮触发doSort()函数时,我可以看到集合已正确排序,但是复合视图不会对“休息”做出反应并继续显示错误的顺序。
如何使复合视图自动对sort()做出反应?
PS:我认为我的代码看起来不错,但它可以在jsfiddle上运行,可以给我一些指导。感谢。答案 0 :(得分:7)
以下是修改过的代码的工作示例:http://jsfiddle.net/AUZrY/1/
您的原始代码存在一些问题:
appendHtml
无法附加子视图