Filtering the Backbone.js Collection by Index

I have a collection of Backbone.js that contains (for example) 30 elements.

I want to go to my collection of filtered filters, consisting of every third element in the source collection.

Does anyone know how to do this elegantly? CoffeeScript code is preferred.

+4
source share
2 answers

Assuming 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 cycling through each existing model and adds only a new collection if the index is a multiple of 3.

You can do this a little better by using the underline method each , opened 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 
+6
source

The layout collection contains several useful underlining methods . You can use filter to get an array of models that you can pass to the template:

 filteredModels = collection.filter (model, i) -> i % 3 == 0 

Alternatively, you can use array understanding; although I think this is less readable ...

 filteredModels = (model for model, i in collection.models when i % 3 == 0) 

If you really need the Backbone.Collection template in your template, you can create a new one with these filtered models:

 filteredCollection = new Backbone.Collection filteredModels 

Here is a working jsfiddle example.

+2
source

Source: https://habr.com/ru/post/1403079/


All Articles