我正在使用Backbone.js来呈现一个项目列表,例如Books。在呈现列表之后,用户可以选择对它们进行排序。因此,如果用户单击按标题排序或按作者姓名排序,列表将在客户端自动排序。
window.Book = Backbone.Model.extend({
defaults: {
title: "This is the title",
author: "Name here"
},
在主干应用程序的上下文中使用来完成此排序的最佳方式是什么。我在AppView中使用jQuery dom排序器吗?
发布于 2012-01-10 19:02:37
您可以更新比较器函数,然后调用排序方法。
// update comparator function
collection.comparator = function(model) {
return model.get('name');
}
// call the sort method
collection.sort();
视图将自动重新呈现。
发布于 2011-08-10 13:25:25
comparator
正是您所需要的
var PhotoCollection = Backbone.Collection.extend({
model: Photo,
comparator: function(item) {
return item.get('pid');
}
});
发布于 2015-10-27 12:03:15
这种方式工作良好,可以动态地按所有attributes
排序,并处理ascending
或descending
var PhotoCollection = Backbone.Collection.extend({
model: Photo,
sortByField: function(field, direction){
sorted = _.sortBy(this.models, function(model){
return model.get(field);
});
if(direction === 'descending'){
sorted = sorted.reverse()
}
this.models = sorted;
}
});
https://stackoverflow.com/questions/7005411
复制相似问题