Backbone.js: How to filter a collection of objects with an array of model identifiers?

I have a Backbone.Collection full of models; let's say that the model is Car . This collection is a large, large list of Cars . I want to have several specific car identifiers selected from the list, and then be able to get only those selected car objects from this collection.

My code block below does not work; I am sure there is a way to do this using Backbone.js / Underscore.js ... I am pretty fresh for Backbone / Underscore.

 CarList = Backbone.Collection.extend({ model: Car, filterWithIds: function(ids) { return this.filter(function(aCar) { return _.contains(ids, car.id); } } }); 

Any pointers?

+6
source share
1 answer

Well, I think I have it. This is close to my source code, but the updated filterWithIds function is here.

 filterWithIds: function(ids) { return _(this.models.filter(function(c) { return _.contains(ids, c.id); })); } 

For those who are next in CoffeeScript (I), here is the CoffeeScript version.

 filterWithIds: (ids) -> _(@models.filter (c) -> _.contains ids, c.id) 

This is my answer; any smell of code?

+12
source

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


All Articles