javascript - backbonejs get Models for a list of ids - Stack Overflow

admin2025-04-26  8

To get a single model from a collection by it's ID I can call

var myObject = myCollection.get(id)

When I have a list of IDs of several models I would like to get, is there a better way to get them from a collection than calling .get() for each id separately?

The following code snippet does the job but seems to be a bit messy with a lot of requests to the collection.

var idList = new Array(34, 86, 167, 413);
var models = new Array();
for (var i = 0; i < idList.length; ++i) {
  models.push(myCollection.get(idList[i]));
}

thanks
- ben

To get a single model from a collection by it's ID I can call

var myObject = myCollection.get(id)

When I have a list of IDs of several models I would like to get, is there a better way to get them from a collection than calling .get() for each id separately?

The following code snippet does the job but seems to be a bit messy with a lot of requests to the collection.

var idList = new Array(34, 86, 167, 413);
var models = new Array();
for (var i = 0; i < idList.length; ++i) {
  models.push(myCollection.get(idList[i]));
}

thanks
- ben

Share Improve this question edited Sep 3, 2016 at 12:54 Benjamin asked Nov 10, 2013 at 13:44 BenjaminBenjamin 8138 silver badges12 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

Actually it's not messy at all and you're only calling get on the collection 4 times. Even if Backbone allowed you to "get" multiple ids at a time, on the backend of things it'd still be doing about the same amount of work.

You could perhaps rewrite things a bit so they are a bit easier on the eyes, but that's more your personal preference. I'd probably do something like this using alternate forms of the array and for loop notation.

var ids = [34, 86, 167, 413];
var selected = [];
for (var i in ids)
    selected.push(myCollection.get(ids[i]));

If you're going to be doing it a lot and want to make it look even cleaner you could use a filter to return a smaller collection like mu mentioned.

filterBy: function(attribute, value) {
    var filtered = this.filter(function(items) {
        return _.contains(value, items.get(attribute));
    });
    return new myCollection(filtered);
}

var newFilteredCollection = myCollection.filterBy('id', [34, 86, 167, 413]);

If you've got Backbone, you've got underscore (or LoDash), so how about this?

var ids = [34, 86, 167, 413];
var selected = _.map(ids, function (id) {
  return myCollection.get(id);
});

Or, as a utility function (could be added to the Backbone.Collection prototype):

/**
 * @param {Number[]}ids
 * @returns {Backbone.Model[]}
 */
getForIds: function (ids) {
  return _.map(ids, function (id) {
    // replace "myCollection" with "this" if extending Backbone.Collection:
    return myCollection.get(id);
  });
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745672570a313402.html

最新回复(0)