scr*_*key 8 javascript backbone.js
我有一个用户列表(确切地说是六个),其中包含'firstname','lastname'属性.进行提取时,下面的比较器按'firstname'对它们进行排序,它运行正常.
comparator : function (user) {
return user.get("firstname").toLowerCase();
}
Run Code Online (Sandbox Code Playgroud)
但是如果我稍后尝试使用不同的值(即'lastname')对集合进行排序,则它不起作用.订单保持不变.
this.collection.sortBy(function(user) {
return user.get("lastname").toLowerCase();
});
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
更新
因此从sortBy IS返回的数据已经排序,但这对我来说并没有帮助,因为我的视图与集合相关联.如果我重置集合并将已排序的数组添加回集合,它的比较器就会完成它的工作,并将其排序回'firstname'顺序.
var sorted = this.collection.sortBy(function(user) {
return user.get("lastname").toLowerCase();
});
Run Code Online (Sandbox Code Playgroud)
obm*_*arg 13
要回复您的更新:
如果您想要更改集合的顺序以供其相应的视图使用,那么您可以只更新comparator然后调用sort以重新排序模型.然后,这将触发sort您的视图可以侦听的事件并相应地更新自身.
this.collection.comparator = function (user) {
return user.get("firstname").toLowerCase();
};
this.collection.sort();
Run Code Online (Sandbox Code Playgroud)
Der*_*ley 12
该sortBy函数不对当前集合中的对象进行排序.它返回一个已排序的集合:
var sortedCollection = this.collection.sortBy(function(user){
return user.get("lastname").toLowerCase();
});
Run Code Online (Sandbox Code Playgroud)
现在你可以使用sortedCollection它,它将被正确排序.