我正在尝试对一组对象进行排序.我不想为每个属性编写自定义排序方法.
无论如何我可以扩展内置array.sort()方法来接受一个额外的参数,描述要排序的属性?例如,
array.sort(function(a, b, attr) { return a.attr - b.attr; }, 'name');
Run Code Online (Sandbox Code Playgroud) 我有点卡住实现了骨干比较器,我基本上想要根据路由选择不同的排序方法,并使用比较器对集合进行排序.理想情况下,我希望将排序逻辑封装在集合中,但似乎陷入困境.例如
Requests = Backbone.Collection.extend({
model : Request,
comparator : function(ab) {
return -ab.id;
},
nooffers : function() {
return this.sortBy(function(ab) {
return ab.get('offers');
});
}
});
Run Code Online (Sandbox Code Playgroud)
因此,默认情况下,它会根据默认比较器进行排序 - 但在我的路由中,我希望能够采取类似的措施
routes : {
"" : "index",
'/ordering/:order' : 'ordering'
},
ordering : function(theorder) {
ordering = theorder;
if(theorder == 'nooffers') {
Request.comparator = Request.nooffers();
}
Request.sort();
listView.render();
howitworksView.render();
}
Run Code Online (Sandbox Code Playgroud)
但是在那种情况下,我得到一个错误('c.call不是函数')任何想法?