我制作了我的第一个主干应用程序,但在集合排序方面遇到了一些问题。 使用后
var SortedFriends = MyFriends.sortBy(function(friend) {
return friend.get("uid");
});
console.log(SortedFriends) 显示 SortedFriends 包含排序模型,但是当我尝试使用像“SortedFriends.each”或“SortedFriends.at”这样的集合函数时,它会出错:
TypeError:SortedFriends.each 不是函数。
代码:
var Friend = Backbone.Model.extend({});
var Friends = Backbone.Collection.extend({
model: Friend,
});
var MyFriends = new Friends();
MyFriends.reset(<?=$friends?>);
var FriendView = Backbone.View.extend({
initialize: function(){
model:Friend
},
tagName: "tr",
template: _.template($('#item-template').html()),
className: "document-row",
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
var SortedFriends = MyFriends.sortBy(function(friend) {
return friend.get("uid");
});
var addOne = function(element){
var view = new FriendView({model: element});
$("#friends").append(view.render().el);
}
console.log(JSON.stringify(SortedFriends));
SortedFriends.each(function(friend){
var view = new FriendView({model: friend});
$("#friends").append(view.render().el);
});
最佳答案
如果您正在使用 Backbone 集合,那么您最好使用比较器
而不是集合方法
http://backbonejs.org/#Collection-comparator
当您准备好对您的收藏进行分类时:
MyFriends.comparator = function(friend){
return friend.get("uid");
});
MyFriends.sort();
或者如果你想保持未排序集合的顺序,那么你需要先克隆它
http://backbonejs.org/#Collection-clone
var SortedFriends = MyFriends.clone();
SortedFriends.comparator = function(friend){
return friend.get("uid");
});
SortedFriends.sort();
关于javascript - Backbone 集合 sortBy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18010714/