我正在通过向表中添加排序可能性来修改https://github.com/davidsulc/marionette-gentle-introduction。看起来我已经做了我需要做的事情,但桌子没有被刷新。
1)收藏: original collection code
Entities.DeviceCollection = Backbone.Collection.extend({
url: "/devices",
model: Entities.Device,
sortAttribute: "type",
sortDirection: 1,
sortDevices: function(attr) {
this.sortAttribute = attr;
this.sort();
},
comparator: function(a, b) {
var a = a.get(this.sortAttribute),
b = b.get(this.sortAttribute);
if (a == b)
return 0;
if (this.sortDirection == 1) {
return a > b ? 1 : -1;
} else {
return a < b ? 1 : -1;
}
}
});
2)视图:original view code
View.Devices = Marionette.CompositeView.extend({
tagName: "table",
className: "table table-hover",
template: listTpl,
emptyView: NoDevicesView,
itemView: View.Device,
itemViewContainer: "tbody",
sortUpIcon: 'glyphicon glyphicon-chevron-up',
sortDnIcon: 'glyphicon glyphicon-chevron-down',
events: {
"click th": "headerClick"
},
initialize: function() {
this.listenTo(this.collection, "sort reset", function() {
console.log("Sort RESET");
this.appendHtml = function(collectionView, itemView, index) {
collectionView.$el.append(itemView.el);
}
});
},
onRender: function() {
this.$el.find('th div')
.append($('<span>'))
.closest('thead')
.find('span')
.addClass('sort-ic icon-none')
.end()
.find('[column="' + this.collection.sortAttribute + '"] span')
.removeClass('icon-none').addClass(this.sortUpIcon);
},
onCompositeCollectionRendered: function() {
this.appendHtml = function(collectionView, itemView, index) {
collectionView.$el.prepend(itemView.el);
}
},
headerClick: function(e) {
var $el = $(e.currentTarget),
ns = $el.attr('column'),
cs = this.collection.sortAttribute;
console.log('ns:' + ns);
// Toggle sort if the current column is sorted
if (ns == cs) {
this.collection.sortDirection *= -1;
} else {
this.collection.sortDirection = 1;
}
// Adjust the indicators. Reset everything to hide the indicator
$el.closest('thead').find('span').attr('class', 'icon-none');
// Now show the correct icon on the correct column
if (this.collection.sortDirection == 1) {
$el.find('span').removeClass('icon-none').addClass(this.sortUpIcon);
} else {
$el.find('span').removeClass('icon-none').addClass(this.sortDnIcon);
}
// Now sort the collection
this.collection.sortDevices(ns);
}
});
这里我添加了一个监听器来排序以刷新视图,但它无法正常工作
initialize: function () {
this.listenTo(this.collection, "sort reset", function() {
console.log("Sort RESET");
this.appendHtml = function(collectionView, itemView, index) {
collectionView.$el.append(itemView.el);
}
});
},
问题出在哪里?
答案 0 :(得分:1)
用户2814599的另一个答案的简短版本:
View.Devices = Marionette.CompositeView.extend({
// Omitted other attributes
collectionEvents: {
'sort': 'render'
}
});
答案 1 :(得分:0)
我所要做的就是在视图的初始化方法中添加一个监听器,以便在每个排序事件上调用this.render():
initialize: function () {
this.listenTo(this.collection, "sort", function () {
this.render();
});
},