【问题标题】:In Ember.js how do I create a computed property that references first item in property containing an array在 Ember.js 中,如何创建一个计算属性,该属性引用包含数组的属性中的第一项
【发布时间】:2014-03-19 00:55:09
【问题描述】:

我的测验装置有一个名为 questions 的属性,它是相关问题的 id 数组。我想在名为 firstQ 的模型上创建一个计算属性,该属性返回问题数组中的第一个 id。最终,我想使用该 ID 并使用它链接到我创建的问题路线。

我不知道如何访问问题数组中的第一个 ID。这甚至是解决这个问题的最佳方法吗?请帮忙。

App.ApplicationAdapter = DS.FixtureAdapter.extend();

App.Quiz = DS.Model.extend({
  name: DS.attr('string'),
  description: DS.attr('string'),
  questions: DS.hasMany('question', {async: true}),
  firstQ: function() {
    return this.get('questions')//where to go next?, on right track?;
  }.property()
});

App.Question = DS.Model.extend({
  question: DS.attr('string'),
  quiz: DS.belongsTo('quiz', {async: true}),
  answers: DS.attr('string')
});

//fixtures
App.Quiz.FIXTURES = [
  {
    id: 1,
    name: 'The JavaScript Quiz',
    description: 'take this quiz and find out if you\'re a super genious',
    questions: [100,101]
  }
];

App.Question.FIXTURES = [
  {
    id:100,
    question: 'Inside which HTML element do we put the JavaScript',
    quiz: 1,
    answers: [
      { answer: 'alpha', weight: 0 },
      { answer: 'beta', weight: 5 }
    ]
  }
]

【问题讨论】:

    标签: javascript ember.js ember-data


    【解决方案1】:

    好的,所以我想出了如何通过模型上的计算属性来做到这一点。这是 App.Quiz 模型的更新代码:

    App.Quiz = DS.Model.extend({
      name: DS.attr('string'),
      description: DS.attr('string'),
      questions: DS.hasMany('question', {async: true}),
      firstQuestion: function() {
        return this.get('questions.firstObject');
      }.property('questions.firstObject')
    });
    

    【讨论】:

      【解决方案2】:

      您可以使用 Ember 数组的 firstObject 属性在 firstQquestions 数组中的第一个 Id 之间创建绑定。将您的 firstQ 属性定义为这样的绑定

      App.Quiz = DS.Model.extend({
        name: DS.attr('string'),
        description: DS.attr('string'),
        questions: DS.hasMany('question', {async: true}),
        firstQBinding: 'questions.firstObject'
      });
      

      【讨论】:

      • 谢谢,但我遇到了错误。加载路由时出错:TypeError:无法读取未定义的属性“问题”
      猜你喜欢
      • 1970-01-01
      • 2013-06-29
      • 1970-01-01
      • 2016-07-11
      • 2016-08-24
      • 2021-12-09
      • 1970-01-01
      • 2020-07-19
      • 2013-02-11
      相关资源
      最近更新 更多