Sorting an async relationship

Hi,

I have an ember app which shows ‘competitions’, each ‘competition’ object has many ‘competitor’ objects:

app/models/competition.js

import DS from "ember-data";

export default DS.Model.extend({
  name: DS.attr('string'),
  competitors: DS.hasMany('competitor', {async: true}),
});

I have a league-table component which is passed a ‘competition’ object as its main data.

app/components/league-table.js

import Ember from "ember";

export default Ember.Component.extend({
  classNames: ['league-table'],
  competition: null,
  visibleCompetitors: Ember.computed.filterBy('competition.competitors', 'hidden', false),
  sortProperties: ['score:desc'],
  sortedCompetitors: Ember.computed.sort('visibleCompetitors', 'sortProperties'),
});

I would like to present the competitors in the correct order as a simple list. The sort order is determined by a complicated ‘score’ property of the competitor which is calculated based on a significant amount of data which is embedded in the competitor object when it is loaded.

app/templates/components/league-table.hbs

<header>
  <h2>{{competition.name}}</h2>
</header>
<ul>
  {{#each sortedCompetitors as |competitor index|}}
      {{competitor-item competitor=competitor}}
  {{else}}
    <li class="centered">competition has no competitors</li>
  {{/each}}
</ul>

The server takes a long time to load the ‘competition.competitors’ list so I was hoping to have the league table populate gradually and have competitors slot into the correct positions as they are loaded.

My problem is that competitor objects are not correctly ordered. I can see this is something to do with the promise but I can’t realistically wait for all the competitors to load before rendering something.

Is there a way to restructure this so the competitors are slotted into the correct positions as they are loaded or do I need to think about the problem in a different way?

Hey! I am encountering the same issue and I am pretty sure it was working fine with previous versions of Ember / Ember data (before 2.0).

Did you find a solution?

Hi, sorry for the late reply,

I reworked this whole thing so that my server pre-calculated the ‘score’ property. This fixed my issue and made my app much more responsive.