Ember计算属性以从列表中返回前X个项目

时间:2014-08-21 19:55:09

标签: ember.js

我有一对多的关系(使用Ember数据)。我想要做的就是在概览(索引)模板中列出该关系中的第一个N项目数。我正在尝试使用Array.slice方法,但它似乎根本没有返回任何内容。

这就是我现在所拥有的:

模型/ account.js

// Account model
import DS from 'ember-data';

export default DS.Model.extend({
  name:   DS.attr('string'),
  notes:  DS.hasMany('note', { async: true })
});

模型/ note.js

// Note model
import DS from 'ember-data';

export default DS.Model.extend({
  body:     DS.attr('string'),
  date:     DS.attr('number'), // unix timestamp
  account:  DS.belongsTo('account', { async: true })
});

控制器/帐户/ index.js

// account/index controller
import Ember from 'ember';

export default Ember.ObjectController.extend({
  firstNotes: function() {
    return this.get('notes').slice(0,2);
  }.property('notes')
});

模板/帐户/ index.hbs

{{!-- this lists all the associated `Notes` --}}
{{#each notes}}
  {{date}}<br>
  {{body}}
{{/each}}


{{!-- this doesn't list anything!!?? --}}
{{#each firstNotes}}
  {{date}}<br>
  {{body}}
{{/each}}

1 个答案:

答案 0 :(得分:2)

我想出来就像我要张贴它所以我想我会回答它...

我失踪的是计算属性依赖项中的@each。所以它按预期工作:

firstNotes: function() {
   return this.get('notes').slice(0,2);
}.property('notes.@each')

简单。