如何使用不同的控制器为每条记录迭代Ember中的hasMany集合

i0n*_*i0n 2 ember.js ember-data

我在Ember中定义了三个模型,并且根据请求返回所有json:

App.Comment = DS.Model.extend({
    discussion: DS.belongsTo('App.Discussion')
});

App.Discussion = DS.Model.extend({
    meeting: DS.belongsTo('App.Meeting'),
    comments: DS.hasMany('App.Comment')
});

App.Meeting = DS.Model.extend({
    discussions: DS.hasMany('App.Discussion')
});
Run Code Online (Sandbox Code Playgroud)

从会议控制器中的路由会议/:id,我希望能够遍历讨论集合,为每个实例设置新的讨论控制器.然后我需要能够遍历每个讨论评论,再次做同样的事情.目前我似乎能够访问关联中定义的属性,但是如果我调用计算属性,则会返回不正确的结果(例如,当它应为5时,计数为0).我认为这个问题与控制器的上下文有关,因为我似乎无法在控制器中返回该对象的值.它可能非常简单,但我看不到它.我究竟做错了什么?

这是控制器:

App.MeetingController = Ember.ObjectController.extend({
    needs: ['discussion']
});

App.DiscussionController = Ember.ObjectController.extend({
    commentCount: function(){
        return this.get('comments.length');
    }.property('comments')
});
Run Code Online (Sandbox Code Playgroud)

然后在meeting.hbs模板中:

{{#each discussion in discussions}}
    {{ render 'discussion' discussion }}
{{/each}}
Run Code Online (Sandbox Code Playgroud)

和discussion.hbs模板一样,这个工作原理:

<div>
    {{ comments.length }}
</div>
Run Code Online (Sandbox Code Playgroud)

但这不是:

<div>
    {{ commentCount }}
</div>
Run Code Online (Sandbox Code Playgroud)

我哪里错了?

Ted*_*nny 6

我认为问题在于您如何定义计算属性,看起来绑定不起作用.

请尝试使用.property('comments.@each'):

App.DiscussionController = Ember.ObjectController.extend({
  commentCount: function(){
    return this.get('comments.length');
  }.property('comments.@each')
});
Run Code Online (Sandbox Code Playgroud)

2014年7月10日更新:您现在可以使用:

App.DiscussionController = Ember.ObjectController.extend({
  commentCount: Ember.computed.oneWay('comments.length')
});
Run Code Online (Sandbox Code Playgroud)

  • 特迪你是一个学者和绅士,谢谢你! (3认同)