我有一个在表格中呈现的骨干集合。我想根据集合具有的某些属性使表格可排序,例如“task_status”、“task_group”。我正在阅读有关 collection.comarator 和 collection.sort 的主干文档。我怎样才能完成这项工作?
3 回答
该comparator
函数用于比较集合中的两个模型,并且可以以任何(一致的)它想要的方式比较它们。特别是,它可以选择使用哪个模型属性,这样你的集合中就可以有这样的东西:
initialize: function() {
this.sort_key = 'id';
},
comparator: function(a, b) {
// Assuming that the sort_key values can be compared with '>' and '<',
// modifying this to account for extra processing on the sort_key model
// attributes is fairly straight forward.
a = a.get(this.sort_key);
b = b.get(this.sort_key);
return a > b ? 1
: a < b ? -1
: 0;
}
然后你只需要集合上的一些方法来改变sort_key
and 调用sort
:
sort_by_thing: function() {
this.sort_key = 'thing';
this.sort();
}
在较旧的 Backbones 中,调用sort
将触发一个"reset"
事件,而较新的版本将触发一个"sort"
事件。要涵盖这两种情况,您可以同时监听事件并重新渲染:
// in the view...
initialize: function() {
this.collection.on('reset sort', this.render, this);
}
演示:http: //jsfiddle.net/ambiguous/7y9CC/
initialize: function() {
this.listenTo(this.collection, 'reset sort', this.render);
}
演示:http: //jsfiddle.net/ambiguous/nG6EJ/
@mu-is-too-short 的答案很好,除了有一种更简单的方法来比较字段值:
根据字段对集合进行排序的最简单方法是提供一个比较器函数,该函数返回您要排序的确切字段值。这种比较器导致 Backbone 调用sortBy
函数,而不是sort
,然后它自己进行复杂的比较,您不必担心逻辑。
所以本质上,您不必提供复杂的比较器功能,除非您对确定顺序有更高级的需求。
var myCollection = Backbone.Collection.extend({
sort_key: 'id', // default sort key
comparator: function(item) {
return item.get(this.sort_key);
},
sortByField: function(fieldName) {
this.sort_key = fieldName;
this.sort();
}
});
在此之后,您可以sortByField
使用代表您要排序的键的字符串调用集合的 -function。例如:
collection.sortByField('name');
修改了@my-is-too-short 的演示:http: //jsfiddle.net/NTez2/39/
@jylauril 的回答非常有帮助,但需要修改演示(可能自发布以来主干略有变化?)
看起来您需要在排序后触发渲染。
$('#by-s').click(function() {
c.sortByField('s');
v.render();
});
更新了@my-is-too-short 的演示:http: //jsfiddle.net/NTez2/13/