Skip to content Skip to sidebar Skip to footer

Sort Ember Object Array With Promises

I have a model model/person { firstName: DS.attr( 'string'), lastName: DS.attr( 'string'), email: DS.attr( 'string' ), } and another model model/project { name:

Solution 1:

The solution is simply to use .@each:

renderProjects: computed ('model.projects.@each.firstName', function() {
  return this.users.sortBy('firstName');
})

this will recompute the renderProjects CP whenever the list of projects change or any firstName on any of the projects changes and then automagically update your view.

One important notice: You can not do .@each.foo.bar. This is what you did in your twiddle with model.@each.myUser.name.

In your twiddle the easiest fix is to add a computed.alias to the video model:

username: computed.alias('myUser.name'),

Then you can do this:

sortedVideos: computed('model.@each.username', function() {
  return this.get('model').sortBy('username');
})

Here is a fixed twiddle.


Solution 2:

I would implement an observer, which watches the project array. Inside of the observer I would resolve the users-relationship sort the project array subsequently.

Please check out following code snippet.

  modelObserver: observer('model.[]', function() {
    let userPromises = this.get('model').map(project => project.get('users'));
    RSVP.all(userPromises).then(function() {
      this.set('sortedProjects', this.get('model').sortBy('users.firstObject.name'));
    }.bind(this));
  })

Post a Comment for "Sort Ember Object Array With Promises"