2012-08-17 70 views
0

我想在将它传递给模板之前对其进行排序。我在我看来如何在Backbone中对集合进行排序

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; 
  1. 有没有借助任何其他方式,而我可以收集传递给模板?
  2. 如何根据模型的字符串字段来排序集合,比如Model.name?我试着在集合中编写一个比较器,并在视图中排序函数,但不幸的是;它亘古不变的工作对我来说
+0

对不起给出的例子,但与提供的代码片段,没有太大的帮助是可能的。在您的代码中,您没有将任何收集数据传递给模板,您的渲染函数未提供,您的比较器是什么样的,........请提供完整的代码 – schacki 2012-08-17 12:44:08

回答

0

有没有其他办法可以通过我可以将该集合传递给 模板?

是的,集合的有toJSON() method所以你可以简单地这样做

render: function() { 
    this._template({list: this.toJSON()}); //assuming your template is already compiled 
    return this; 
} 

你如何排序基于模型的字符串字段集合,说 Model.name?我试图在集合中写一个比较器,并且不幸的是,它不工作,我

您可以简单地定义在集合comparator功能,它应该保持自身的排序,这里是在文档

chapters.comparator = function(chapter) { 
    return chapter.get("page"); 
}; 
1

实现你Collectioncompatarator功能,在docs定义为

如果定义了一个比较,它会被用来维持有序集合 。

这样你的收藏就会增加后,会自动保存在一个有序,删除等,您可以实现它作为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'); 
} 

希望这有助于!

相关问题