Hari Pachuveetil
Hari Pachuveetil

Reputation: 10374

Finding a few records by id using ember-data

I am trying to load a few favorite repositories for the Travis-CI Mobile I am trying to put together here

What I have is an array of repository IDs like this:

var favoriteRepos = ["668498","557554","7934","207993"];

How could we go about loading all these repos with the ember-data revision 12, the Travis custom RESTAdapter and the Travis API?

This is what I have tried unsuccessfully so far:

// This is in the repo model - https://github.com/floydpink/Travis-CI-www/blob/master/js/app/models/Repo.js
Repo.reopenClass({
  favorites     : function (favorites) {
    // favorites would be an array of repo-ids like  ["451069","538603"]
    var faves = Ember.ArrayProxy.create({
      isLoadedBinding : 'content.isLoaded',
      content         : Ember.A([])
    });
    favorites.forEach(function (favorite) {
      faves.pushObject(Repo.find(favorite));
    });
    return faves;
  }
});

// And in FavoritesController
this.set('content', Repo.favorites(favoriteRepos));

So the generic question is, how do we go about loading a few different records by id, using ember-data?

Upvotes: 0

Views: 493

Answers (2)

Peter Wagenet
Peter Wagenet

Reputation: 5056

You should be able to just do:

Repo.reopenClass({
  favorites     : function (favorites) {
    // favorites would be an array of repo-ids like  ["451069","538603"]
    return Ember.ArrayProxy.createWithMixins({
      content: favorites.map(function(id) { return Repo.find(id); }),
      isLoaded: function() {
        return this.everyProperty('isLoaded');
      }.property('@each.isLoaded');
    });
  }
});

Upvotes: 4

Sebastian Seilund
Sebastian Seilund

Reputation: 454

If your handlebars template looks like this:

{{#if isLoaded}}
  {{#each controller}}
    ...
  {{/each}}
{{/if}}

Then it won't work because you never set isLoaded to true on your array. Depending on which data implementation you use, you could do something like this:

Repo.reopenClass({
  favorites: function (ids) {
    // ids would be an array of repo-ids like  ["451069","538603"]
    var loadCount = 0;
    var favorites = Em.A();
    ids.forEach(function(id) {
      var favorite = Repo.find(id);
      favorites.pushObject(favorite);
      favorites.then(function() {
        loadCount++;
        if (loadCount == ids.length) {
          favorites.set('isLoaded', true);
        }
      });
    });
    return favorites;
  }
});

The isLoaded property is set to true once all favorites have been loaded from the server.

Upvotes: 1

Related Questions