我在实现一个主干比较器时遇到了一些问题,我基本上想根据路由选择不同的排序方法,并使用比较器对集合进行排序。理想情况下,我希望将排序逻辑封装在集合中,但似乎被卡住了。例如
Requests = Backbone.Collection.extend({
model : Request,
comparator : function(ab) {
return -ab.id;
},
nooffers : function() {
return this.sortBy(function(ab) {
return ab.get('offers');
});
}
}); 因此,默认情况下,它基于默认的比较器进行排序-但在我的路由中,我希望能够重新排序,例如,执行以下操作
routes : {
"" : "index",
'/ordering/:order' : 'ordering'
},
ordering : function(theorder) {
ordering = theorder;
if(theorder == 'nooffers') {
Request.comparator = Request.nooffers();
}
Request.sort();
listView.render();
howitworksView.render();
}然而,在这种情况下,我得到一个错误('c.call不是一个函数‘),有什么想法吗?
发布于 2012-02-25 02:28:00
这里有一些地方是错误的。
这并不是你所想的那样:
if(theorder == 'nooffers') {
Request.comparator = Request.nooffers();
}它执行nooffers方法并将其结果赋值给Request.comparator。但是sortBy返回排序后的列表:
nooffers : function() {
return this.sortBy(function(ab) {
return ab.get('offers');
});
}并且将该列表设置为比较器函数不会做任何有用的事情。
您希望更改赋值以使用函数,而不是其返回值:
if(theorder == 'nooffers') {
Request.comparator = Request.nooffers;
}并将该函数更改为有效的比较器函数:
nooffers : function(ab) {
return ab.get('offers');
}演示(打开控制台运行):http://jsfiddle.net/ambiguous/AAZCa/
但是,让外部的人像这样摆弄集合的方法是很糟糕的,你不应该这样做。相反,您应该要求集合更改其顺序,如下所示:
var Requests = Backbone.Collection.extend({
model: Request,
comparator: function(ab) {
if(this._order_by == 'offers')
return ab.get('offers');
else if(this._order_by == 'id')
return -ab.id;
//...
},
order_by_offers: function() {
this._order_by = 'offers';
this.sort();
},
order_by_default: function() {
this._order_by = 'id';
this.sort();
},
_order_by: 'id'
});
//...
rs.order_by_offers();演示:http://jsfiddle.net/ambiguous/uM9av/
或者,您可以让集合交换自己的comparator,以避免comparator中的所有条件逻辑
var Requests = Backbone.Collection.extend({
model: Request,
initialize: function() {
this._order_by_id = this.comparator;
},
comparator: function(ab) {
return -ab.id;
},
order_by_offers: function() {
this.comparator = this._order_by_offers;
this.sort();
},
order_by_default: function() {
this.comparator = this._order_by_id;
this.sort();
},
_order_by_offers: function(ab) {
return ab.get('offers');
}
});演示:http://jsfiddle.net/ambiguous/Pjfq2/
https://stackoverflow.com/questions/9431171
复制相似问题