这是我的应用程序的代码示例
讨论模型
App.Discussion = Ember.Model.extend({
id: Ember.attr(),
title: Ember.attr(),
body: Ember.attr(),
course_id: Ember.attr(),
replies: Ember.hasMany('App.Reply', {key:'replies', embedded: 'load'}),
creator_id: Ember.attr(),
creator_first_name: Ember.attr(),
creator_last_name: Ember.attr(),
status: Ember.attr(),
created_at: Ember.attr(),
accepted_answer_id: Ember.attr()
});
回复模型
App.Reply = Ember.Model.extend({
id: Ember.attr(),
body: Ember.attr(),
discussion_id: Ember.attr(),
discussion: Ember.belongsTo('App.Discussion', {key: 'discussion_id'}),
creator_id: Ember.attr(),
creator_first_name: Ember.attr(),
creator_last_name: Ember.attr(),
status: Ember.attr(),
created_at: Ember.attr()
});
App.Discussion.Controller = Ember.ObjectController.extend({
hasSomething: function() {
// Here I want to check whether user_id = 101 in the replies array of the discussion Model.
// If any of the replies has the user_id as 101 return true.
}.property('id')
});
我尝试将回复放入数组中,然后迭代并检查它。
replies = this.get('model.replies');
replies.forEach(function(reply) {
console.log(reply.get('creator_id'));
if (window.userId === reply.get('creator_id')) {
// do stuff here.
}
});
有没有更好的/ EMBER方式来实现这个???
答案 0 :(得分:2)
Ember在他们的Array-object上有一些很好的帮手(除非你禁用原型扩展,否则也可以在常规阵列上使用)。
Array.isAny()可能值得一看。
hasSomething: function() {
// Here I want to check whether user_id = 101 in the replies array of the discussion Model.
// If any of the replies has the user_id as 101 return true.
var replies = this.get('model.replies');
return replies.isAny('creator_id', window.userId);
}.property('model.replies.@each')
您可能还希望将属性设置为使用model.replies.@each
实际观察回复数组。