Sort Ember Object Array with Promises

无人久伴 提交于 2019-12-11 10:57:12

问题


I have a model model/person

{

  firstName: DS.attr( 'string'),
  lastName: DS.attr( 'string'),
  email: DS.attr( 'string' ),
}

and another model model/project

{

  name:            DS.attr( 'string' ),
  code:            DS.attr( 'string' ),
  startDate:       DS.attr( 'date' ),
  endDate:         DS.attr( 'date' ),
  users : DS.hasMany('person', {async: true}),

}

then i'm retrieving all the projects with as an array which contains ember objects. since the project -> users is async its a promise. and i want to sort that array using the first name of the person. when the data is arrived accordingly and re render the hbs that is using the list

i have a computed property called

renderProjects = computed ('model.projects.[]')
{
 // trying to sort in here but data is not avaiable so its not getting sorted
}

回答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.




回答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));
  })


来源:https://stackoverflow.com/questions/53422860/sort-ember-object-array-with-promises

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!