在ember.js objectController中按属性排序

时间:2013-08-23 15:53:10

标签: javascript ember.js ember-data

我有一个测验视图,我想按问题ord属性对其进行排序。如果测验的唯一属性是问题,这将很简单,但我有一个模型结构,如下所示:

测验模型

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

问题模型

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

因此,创建的控制器是对象控制器,而不是阵列控制器。关于如何按该属性排序的任何想法?

1 个答案:

答案 0 :(得分:2)

好的,Ember有Ember.ArrayProxy和Ember.SortableMixin,所以你可以这样做:

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

它还有很多其他选项,你可以在那里查看https://github.com/emberjs/ember.js/blob/master/packages/ember-runtime/lib/mixins/sortable.js,你可以找到你可以覆盖的orderBy函数:

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;

}

您甚至可以删除断言,并且不要设置sorProperties,并将其更改为:

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;

}