I have Backbone.js collection that holds (for example) 30 items.
I want to pass to my template filtered collection consist of every 3rd item in the original collection.
Does anyone know how it can be done elegantly? CoffeeScript code is preferred.
Assuming here that originalCollection
is your existing collection
var newCollection = new Backbone.Collection();
for (var i = 0, l = originalCollection.length; i < l; i++) {
if (i % 3 === 0) { newCollection.add(originalCollection.models[i]); }
}
This code works by looping through each existing model, and only adding the model the new collection if it's index is a multiple of 3.
You could make this a little nicer, by using the underscore each
method exposed by Underscore.js in Backbone Collections:
var newCollection = new Backbone.Collection();
originalCollection.each(function (model, index) {
if (index % 3 === 0) { newCollection.add(model); }
});
Converting the above to CoffeeScript results in:
newCollection = new Backbone.Collection()
originalCollection.each (model, index) ->
newCollection.add model if index % 3 is 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With