javascript Backbone/Underscore sortBy 不排序集合

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9803378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 07:54:05  来源:igfitidea点击:

Backbone/Underscore sortBy is not sorting collection

javascriptbackbone.js

提问by screenm0nkey

I have a list of users (six to be exact) in a collection with 'firstname', 'lastname' properties. Doing a fetch, the comparator below sorts them by 'firstname', and it works fine.

我有一个包含“名字”、“姓氏”属性的集合中的用户列表(准确地说是六个)。进行提取时,下面的比较器按“名字”对它们进行排序,并且工作正常。

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

But if I try to sort the collection later, by a different value i.e. 'lastname', it doesn't work. The order stays the same.

但是,如果我稍后尝试按不同的值(即“姓氏”)对集合进行排序,则它不起作用。顺序保持不变。

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

What am i doing wrong?

我究竟做错了什么?


Update


更新



So the data returned from sortBy IS sorted but that doesn't help me really as my view is linked to the collection. If i reset the collection and add the sorted array back to the collection it's comparator does it's job and sorts it back into 'firstname' order.

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

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

回答by obmarg

To respond to your update:

回复您的更新:

If you're wanting to change the order that the collection is sorted in for use by it's corresponding view then you could just update the comparatorand then call sortto get the model re-sorted. This will then fire a sortevent which your view can listen for and update itself accordingly.

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

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

this.collection.sort();

回答by Derick Bailey

The sortByfunction does not sort the objects in the current collection. It returns a sorted collection:

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


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

Now you can use sortedCollectionand it will be sorted correctly.

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

回答by ggozad

Underscore's sortBywhich Backbone uses, returnsthe sorted collection not sort it in place... To illustrate:

sortByBackbone 使用的下划线返回排序后的集合,而不是原地排序......举例说明:

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);