在传递给模板之前,我想对我的选择进行排序。我在视图的渲染功能中使用
CollectionForTelplate : this.Collection我把它当作
var self = this;
//fetch done here
if (Collection.length > 0) {
_.each(Collection, function(Model) {
JSON.stringify(Model);
}, this);
};
self.Collection = Collection;
self.render;发布于 2012-08-17 13:29:08
还有其他方法可以将集合传递给模板吗?
是的,集合有一个toJSON() method,所以您可以简单地做一些类似的事情
render: function() {
this._template({list: this.toJSON()}); //assuming your template is already compiled
return this;
}如何根据模型的string字段对集合进行排序,比如Model.name?我尝试在集合中编写一个比较器,并在视图中编写一个排序函数,但不幸的是,它对我不起作用。
您可以简单地在集合上定义比较器函数,并且它应该保持排序,下面是文档中给出的示例
chapters.comparator = function(chapter) {
return chapter.get("page");
};发布于 2012-08-17 12:43:05
实现Collection的compatarator函数,在文档中定义为
如果您定义了一个比较器,它将用于按排序顺序维护集合。
这样,您的集合将在添加、删除等之后自动按排序顺序保存。您可以将其实现为sort。
comparator: function(model1, model2) {
if (model1 comes before model 2) {
return -1;
} else if (model1 is equal to model 2) {
return 0;
} else { // model1 comes after model 2
return 1;
}
}或sortBy
comparator: function(model) {
// Return some numeral or string attribute and it will be ordered by it
// == smaller numbers come first / strings are sorted into alphabet order
return model.get('someAttribute');
}希望这能有所帮助!
https://stackoverflow.com/questions/12005898
复制相似问题