How is Sorting achieved in an Ember model without using Array Controller?

Abhilash L R picture Abhilash L R · May 22, 2015 · Viewed 9.8k times · Source

Every google result is about an ArrayController sorting. Need a sorting mechanism without using ArrayController.

There is a model where there are sort params. Like say 'sortOrder' as one of the properties in the model (which will be from a back end).

Will be rendering this model using #each but this should do the iteration based on the sortOrder property and not the model's ID property.

Answer

mp31415 picture mp31415 · Jul 24, 2015

In Ember 2.0 SortableMixin is deprecated and is on its way out too.

In the Controller (not the ArrayController) you may define a new computed property like SortedUsers1,2,3 below:

export default Ember.Controller.extend({
    sortProps: ['lastName'],
    sortedUsers1: Ember.computed.sort('model', 'sortProps'),
    sortedUsers2: Ember.computed.sort('content', 'sortProps'),
    sortedUsers3: Ember.computed('content', function(){
        return this.get('content').sortBy('lastName');
    })
});

The assumption above is that the model itself is an array of users with lastName as one of user properties. Dependency on 'model' and 'content' look equivalent to me. All three computed properties above produce the same sorted list.

Note that you cannot replace 'sortProps' argument with 'lastName' in sortedUsers1,2 - it won't work.

To change sorting order modify sortProps to

sortProps: ['lastName:desc']

Also if your template is in users/index folder then your controller must be there as well. The controller in users/ would not do, even if the route loading model is in users/.

In the template the usage is as expected:

    <ul>
        {{#each sortedUsers1 as |user|}}
            <li>{{user.lastName}}</li>
        {{/each}}
    </ul>