简体   繁体   English

在ember.js objectController中按属性排序

[英]Sort by property in an ember.js objectController

I have a Quiz view and I want to sort it by the question ord property. 我有一个测验视图,我想通过问题ord属性对其进行排序。 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? 关于如何按该属性排序的任何想法?

Ok, so, Ember has Ember.ArrayProxy and Ember.SortableMixin, so, you can do something like this: 好的,所以,Ember有Ember.ArrayProxy和Ember.SortableMixin,所以你可以这样做:

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: 它有很多其他选项,你可以看一下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;

} }

you could even remove the assert, and do not set sorProperties, and change it to something like this: 您甚至可以删除断言,并且不要设置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;

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM