Troy Cosentino
Troy Cosentino

Reputation: 4778

creating a backbone collection from array of id values

I have an array of 20 id's pertaining to a certain model.

[4,16,43,34....]

I want to create a collection containing the models represented by those ID values. I was suggested to use map to do it:

arr = arr.map(function(id) { return getModel(id); });

but there wouldn't be any way to have a success function or callback when the whole process was done. I can't perform the next task until this is complete.

Any tips on how I could do this? Thanks

Upvotes: 0

Views: 1274

Answers (1)

jevakallio
jevakallio

Reputation: 35950

I once made this fetchMany mixin for Backbone collections, which does pretty much exactly what you are after, plus some some sugar around the jQuery promise API. Maybe it would be useful for you, too?

The mixin:

Backbone.Collection.prototype.fetchMany = function(ids, options) {
  var collection = this;
  var promises = _.map(ids, function(id) {
    var instance = collection.get(id);
    if(!instance) {
      instance = new collection.model({id:id});
      collection.add(instance);
    }
    return instance.fetch(options);
  });
  //promise that all fetches will complete, give the collection as parameter
  return $.when.apply(this, promises).pipe(function() { return collection; });
};

It can be used so:

var collection = new SomeCollection();
collection.fetchMany([4,16,43,34]).then(function(c) {
  //do something with the collection...
  $("body").append(new SomeView({collection:c}).render().el);
});

Upvotes: 1

Related Questions