Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

backbonejs get Models for a list of ids

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

like image 233
Benjamin Avatar asked Jan 30 '26 11:01

Benjamin


2 Answers

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]);
like image 84
Joshua Avatar answered Feb 01 '26 01:02

Joshua


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);
  });
}
like image 35
Lambart Avatar answered Feb 01 '26 01:02

Lambart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!