Backbone/Undercore sortBy未对集合进行排序

Backbone/Underscore sortBy is not sorting collection

本文关键字:集合 排序 Undercore sortBy Backbone      更新时间:2023-09-26

我在一个具有"firstname"、"lastname"属性的集合中有一个用户列表(确切地说是六个)。在进行提取时,下面的比较器会按照"名字"对它们进行排序,而且效果很好。

comparator : function (user) {
  return user.get("firstname").toLowerCase();
}

但是,如果我稍后尝试按不同的值(即"lastname")对集合进行排序,则不起作用。订单保持不变。

this.collection.sortBy(function(user) {
  return user.get("lastname").toLowerCase();
});

我做错了什么?


更新


因此,从sortBy返回的数据是排序的,但这对我没有真正的帮助,因为我的视图链接到集合。如果我重置集合并将排序后的数组添加回集合,它的比较器会完成它的工作,并将其按"firstname"顺序排序。

var sorted = this.collection.sortBy(function(user) {
  return user.get("lastname").toLowerCase();
});

要响应您的更新:

如果您想更改集合的排序顺序以供其相应视图使用,那么您可以更新comparator,然后调用sort来重新排序模型。然后,这将触发一个sort事件,您的视图可以侦听该事件并相应地更新自身。

this.collection.comparator = function (user) {
  return user.get("firstname").toLowerCase();
};
this.collection.sort();

sortBy函数不对当前集合中的对象进行排序。它返回一个已排序的集合:


var sortedCollection = this.collection.sortBy(function(user){
  return user.get("lastname").toLowerCase();
});

现在您可以使用sortedCollection,它将被正确排序。

Backbone使用的Undercore的sortBy返回已排序的集合而未将其排序到位。。。举例说明:

var flinstones = [{first: 'Baby', last: 'Puss'}, {first: 'Fred', last: 'Flinstone'}];
var sorted = _.sortBy(flinstones, function (character) { return character.last ; });
console.log(sorted);
console.log(flinstones);