For most scenarios involving sorting it's recommented to use Ember.SortableMixin
, which is baked into Ember.ArrayController
.
Please refer to this conceptual example in JSFiddle: http://jsfiddle.net/schawaska/tbbAe/
In this sample the model has a DateTime
field named when
, which I'm using for filtering:
App.Greeting = DS.Model.extend({
text: DS.attr('string'),
when: DS.attr('date')
});
App.Greeting.FIXTURES = [
{id: 1, text: 'First', when: '3/4/2013 2:44:52 PM'},
{id: 2, text: 'Second', when: '3/4/2013 2:44:52 PM'},
{id: 3, text: 'Third', when: '3/4/2013 2:44:52 PM'},
{id: 4, text: 'Fourth', when: '3/4/2013 3:44:52 PM'}
];
In the controller the only thing I have to do is to set the name of the property and the sorting direction:
App.SortingMixinController = Em.ArrayController.extend({
sortProperties: ['when'],
sortAscending: false
});
Then in my Handlebars template, I can use the {{each}}
helper as I would do normally.
Because in this sample, all the dates are the same except for the Forth (which because of sorting appears first), and also because of SortableMixin
, these values will be sorted through another property - I'm assuming the Id here.
The other approach I've taken in that fiddle is using a computed property. I'm not really sure about that approach as it seems to consume more resources and the code in App.SortingPropertyController
is worthy of laugh, but sort of works to show possibilities.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…