2012-03-21 114 views
8

我所拥有的用户(六是精确的)与“名字”,“姓氏”属性的集合在列表中。做一个fetch,下面的比较器按'firstname'对它们进行排序,并且它工作正常。骨干/下划线sortBy不分类收集

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

但如果我尝试收集后进行排序,通过不同的值,即“姓”,这是行不通的。订单保持不变。

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

我在做什么错?


更新


所以从sortBy返回的数据进行排序,但因为我的看法是链接到集合,并不能帮助我真的。如果我重新收集并添加排序的数组回到集合这是比较它的工作并对其排序,返回到“姓名”的顺序。

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

回答

11

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


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

现在你可以使用sortedCollection它会被正确排序。

+0

由于德里克。并感谢您的网站。这是一个伟大的开发人员资源。 – screenm0nkey 2012-03-21 13:35:44

+0

是不是比较函数应该返回整数? – 2012-03-22 08:41:42

+2

请注意,这将返回一个列表而不是一个集合。不是一个很大的交易,但值得一提。 – Chris 2013-06-15 08:10:33

3

下划线的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); 
+1

+1感谢您的回复。 – screenm0nkey 2012-03-21 13:34:49

13

为您更新回应改变这种状况的收集是由它排序中使用的顺序是相应的视图然后你可以只更新comparator,然后调用sort得到模型重新排序。那么这将触发一个sort事件,您认为可以监听并相应地更新自己。

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

this.collection.sort(); 
+0

+1感谢您的回复。那就是我现在要做的。 – screenm0nkey 2012-03-21 13:34:34

+0

这绝对是这里最好的答案。 – Chris 2013-06-15 07:45:08