Cully Mason
Cully Mason

Reputation: 463

Sort by property in an ember.js objectController

I have a Quiz view and I want to sort it by the question ord property. This would be simple if the only property of the quiz were the questions, but I have a Model structure that looks like this:

Quiz Model

App.Quiz = DS.Model.extend({
'badge': DS.belongsTo('App.Badge'),
'passingScore': DS.attr('number'),
'allowed': DS.attr('number'),
'questions': DS.hasMany('App.Question')
})

Question Model

App.Question = DS.Model.extend({
'quiz': DS.belongsTo('App.Quiz'),
'text': DS.attr('string'),
'ord': DS.attr('number'),
'answers': DS.hasMany('App.Answer')
})

So the controller created is an Object Controller and not an Array Controller. Any ideas on how to sort by that property?

Upvotes: 0

Views: 1420

Answers (1)

fanta
fanta

Reputation: 1489

Ok, so, Ember has Ember.ArrayProxy and Ember.SortableMixin, so, you can do something like this:

var sortedElements = Ember.ArrayProxy.createWithMixins(Ember.SortableMixin, {
  content: yourElements.toArray(),
  sortProperties: ['propertyYouWantToSortBy'],
  sortAscending: false
});

and it has many other options, you can take a look at https://github.com/emberjs/ember.js/blob/master/packages/ember-runtime/lib/mixins/sortable.js there, you can find the orderBy function that you could override:

orderBy: function(item1, item2) {
var result = 0,
    sortProperties = get(this, 'sortProperties'),
    sortAscending = get(this, 'sortAscending'),
    sortFunction = get(this, 'sortFunction');

Ember.assert("you need to define `sortProperties`", !!sortProperties);

forEach(sortProperties, function(propertyName) {
  if (result === 0) {
    result = sortFunction(get(item1, propertyName), get(item2, propertyName));
    if ((result !== 0) && !sortAscending) {
      result = (-1) * result;
    }
  }
});

return result;

}

you could even remove the assert, and do not set sorProperties, and change it to something like this:

orderBy: function(item1, item2) {
var result = 0,
    sortAscending = get(this, 'sortAscending'),
    sortFunction = get(this, 'sortFunction');

// implement your sort logic here, I don't know how you want to sort it
result = sortFunction(get(item1, propertyName), get(item2, propertyName));


return result;

}

Upvotes: 2

Related Questions