Default Sort Property for ManyArray

I have a proposal to include a functionality where we can provide the default sortProperty for a DS.ManyArray. In Most cases we end up using an extra computed property to achieve this. Here is an example use case

App.Commentable = DS.Model.extend
  comments:DS.hasMany('comment',{async:true})
  sortedComments:(->
    @get("comments").toArray().sort((a,b)->
      b.get('createdAt')-a.get('createdAt')
    )
  ).property("comments.@each.isFulfilled")

The above was my use case where I had to sort the comments on the created_at with the most latest being the first. It would have been good if I could do something likes this.

App.Commentable = DS.Model.extend
  comments:DS.hasMany('comment',{async:true,sort:"createdAt"})

It seems that an ArrayController would be the best way to handle this:

App.CommentsController = Em.ArrayController.extend({
  sortProperties: ['createdAt']
});

Or if you don’t want to use an ArrayController then you can use Em.computed.sort http://emberjs.com/api/#method_computed_sort

2 Likes

Thanks I guess the computed_sort method fits the bill perfectly.