按照ember上的时间戳排序数据

时间:2015-06-21 21:29:13

标签: ember.js ember-data ember-cli

我看了几个例子,但是无法进行反向排序,因此新生成的对象位于顶部。

我的可排序项目在组件中,我不认为我正在传递sortProperties& sortAscending正确。

lavender.js:

export default Ember.Controller.extend({
    needs: ['application'],

    sortProperties: ['timestamp'],
    sortAscending: false
});

lavender.hbs

{{#each model.comment as |comment|}}
    {{comment-thread message=comment.message user=comment.user timestamp=comment.timestamp sortProperties=sortProperties sortAscending=sortAscending}}
{{/each}}

comment.js

export default DS.Model.extend({
  message: DS.attr('string'),
  timestamp: DS.attr('date'),

  user: DS.belongsTo('user', {async: true}),
  todo: DS.belongsTo('todo', {async: true}),

});

todo.js(lavender.js的模型)

export default DS.Model.extend({
    title: DS.attr('string'),
    isCompleted: DS.attr('boolean', {defaultValue: false}),
    detail: DS.attr('string', {defaultValue: "add details.."}),

    comment: DS.hasMany('comment', {async: true}),
});

必须有一些我没看到的东西..谢谢!

1 个答案:

答案 0 :(得分:1)

如果您希望自己的方法有效,或者您可以选择其他方法,则必须使用已弃用的Ember.ArrayController代替Ember.Controller

最好的方法是使用Ember.computed宏:

export default Ember.Controller.extend({
    needs: ['application'],

    commentsSorting: ['timestamp:desc'],
    comments: Ember.computed.sort('model.comment', 'commentsSorting')
});

然后,代替model,在模板中迭代comments

您还可以使用计算属性和私有(不鼓励)Ember.ArrayProxy,如下所示:

export default Ember.Controller.extend({
    needs: ['application'],

    comments: Ember.computed('model', 'model.comment', function() {
      return Ember.ArrayProxy.createWithMixins(Ember.SortableMixin, {
        sortProperties: ['timestamp'],
        sortAscending: false,
        content: this.get('model.comment')
      });
    })
});

然后,您可以在模板中迭代comments

{{#each model.comment as |comment|}}
    {{comment-thread message=comment.message user=comment.user timestamp=comment.timestamp}}
{{/each}}

我认为你不需要将排序属性传递给comment-thread,我不是你误解了它是如何工作的。它在控制器中排序,其中包括所有记录,而不是组件,其中每个组件只有1条记录,并且没有对其他记录的引用。