EmberJS - 以相反顺序或按日期顺序显示模型

Jac*_*lin 1 ember.js ember-data

我有一个简单的Ember应用程序,它获得了一系列模型:

App.IndexRoute = Ember.Route.extend({
  model: function() {
    return this.store.find("swap");                                                                                                                     
  }
});
Run Code Online (Sandbox Code Playgroud)

然后我在视图中输出它们就像这样:

{{#each model}}
    output stuff here
{{/each}}
Run Code Online (Sandbox Code Playgroud)

一切正常.我还有一个表单,可以让人们添加这个模型的新实例,它工作正常,并将新记录添加到底部.

但是,我想反向做.据我所知,我有两个选择:

  • 反向输出数组,当添加新数组时,将其添加到顶部,而不是底部
  • 每个模型都有一个createdAt带日期的属性,因此按createdAt属性按降序排列每个模型

我认为第二种选择更有意义,但我不知道如何处理它.

目前我只有一个App.IndexRoute,然后我有一个App.ApplicationController我已经添加了一些自定义属性.我假设我需要添加另一个属性或方法来从商店获取数据并按顺序排序createdAt

com*_*ted 5

杰克,你需要使用sortAscendingsortProperties

App.SomeController = Ember.ArrayController.extend({
    sortProperties: ['order'],
    sortAscending: true
});
Run Code Online (Sandbox Code Playgroud)

编辑 请注意,如果您为ID列使用了一个数字,并且想要按此排序,那么您需要将其显式转换为数字:

/**
 * Explicitly forces the model ID to be viewed as an integer, allowing correct numeric     sorting
 */
order: function() {
    return parseInt(this.get('id'), 10);
}.property('id'),
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,这让我走上正轨!我不得不将我的控制器交换到`ArrayController`(而不仅仅是`Controller`),然后将我的视图更新为`{{#each controller}}`而不是`{{#each model}}`. (2认同)