3

I have this structure:

App.Router.map(function() {
    this.resource('board', {path: '/board'}, function() {
        this.route('new', {path: '/new'});
        this.route('show', {path: '/show/:board_id'});
    });
});

App.Board = DS.Model.extend({
    title: DS.attr('string'),
    initialAmount: DS.attr('number'),
    initialDate: DS.attr('date'),
    boardItems: DS.hasMany('BoardItem'),
    _csrf: DS.attr()
});

App.BoardItem = DS.Model.extend({
    title: DS.attr('string'),
    income: DS.attr('number'),
    outcome: DS.attr('number'),
    date: DS.attr('date'),
    itemType: DS.attr('string'),
    board: DS.belongsTo('Board')
});

App.BoardShowRoute = Ember.Route.extend({
    model: function(params) {
        return this.store.find('board', params.board_id).sort();
    }
});

and in the view, I list the board items like that:

{{#each boardItems}}

what I'm trying to do is sorting the boardItems by date, and I can't find a way of doing it... any ideas?

Thanks!

Dima Feldman
  • 688
  • 1
  • 10
  • 16

2 Answers2

8

You should create a computed property in the controller behind the view

Controller

App.BoardShowController = Em.ObjectController.extend({
  sortedBoardItems: function(){
    return this.get('boardItems').sortBy('date');
  }.property('boardItems.@each.date')
});

Template

{{#each sortedBoardItems}}
Community
  • 1
  • 1
Kingpin2k
  • 47,007
  • 10
  • 75
  • 96
  • Thanks it worked! can you please explain this part: .property('boardItems.@each.date') – Dima Feldman Jun 07 '14 at 18:42
  • yeah, each time a new item is added to `boardItems` or one if the `date` field changes (using proper setters) on any of the `boardItems` it will recalculate the property. – Kingpin2k Jun 08 '14 at 02:42
  • Suppose you want the `boardItems` to be sorted that way every time the `board` is used in the app...would it be a sin to define the `sortedBoardItems` in the model? – leejt489 Mar 31 '15 at 19:51
4

You can wrap the {{#each}}...{{/each}} loop with a {{render}} helper and do the sorting in the controller:

Controller:

App.BoardItemsController = Ember.ArrayController.extend({
  sortProperties: ['date'],
  sortAscending: false // newest first
});

Template:

{{#render "boardItems" boardItems}}
  {{#each arrangedContent}}
     Title: {{title}}
     ...
  {{/each}}
{{/render}}

Using a computed property for doing the sorting will result in completely recomputing the sorted array, each time the boardItems change. This is not the case with the arrangedContent approach described here.

Panagiotis Panagi
  • 9,402
  • 6
  • 49
  • 102