首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >成员js在模型中迭代并检查是否存在值。

成员js在模型中迭代并检查是否存在值。
EN

Stack Overflow用户
提问于 2014-07-30 11:35:45
回答 1查看 1.4K关注 0票数 0

这是我的应用程序中的代码示例

讨论模型

代码语言:javascript
运行
复制
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()
});

应答模型

代码语言:javascript
运行
复制
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')

});

我试着把答复放到一个数组中,然后迭代并检查它。

代码语言:javascript
运行
复制
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.
            }
        }); 

有什么更好的方法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-07-30 11:54:20

恩伯有一些不错的帮助他们的数组对象 (也可以在常规数组,除非你禁用原型扩展)。

Array.isAny()可能值得一看。

代码语言:javascript
运行
复制
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实际观察答复数组。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25035819

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档