lio*_*rix 4 collections filter coffeescript backbone.js
我有Backbone.js集合(例如)30个项目.
我想传递给我的模板过滤集合包含原始集合中的每个第3项.
有谁知道如何优雅地完成它?CoffeeScript代码是首选.
假设这originalCollection是您现有的集合
var newCollection = new Backbone.Collection();
for (var i = 0, l = originalCollection.length; i < l; i++) {
if (i % 3 === 0) { newCollection.add(originalCollection.models[i]); }
}
Run Code Online (Sandbox Code Playgroud)
此代码通过循环遍历每个现有模型来工作,并且只有在新集合的索引是3的倍数时才添加模型.
通过使用eachBackbone Collections中Underscore.js公开的下划线方法,你可以使它更好一些:
var newCollection = new Backbone.Collection();
originalCollection.each(function (model, index) {
if (index % 3 === 0) { newCollection.add(model); }
});
Run Code Online (Sandbox Code Playgroud)
将上面的内容转换为CoffeeScript会导致:
newCollection = new Backbone.Collection()
originalCollection.each (model, index) ->
newCollection.add model if index % 3 is 0
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3244 次 |
| 最近记录: |