在Ember.js中,如何创建一个计算属性,该属性引用包含数组的属性中的第一项 [英] In Ember.js how do I create a computed property that references first item in property containing an array

查看:65
本文介绍了在Ember.js中,如何创建一个计算属性,该属性引用包含数组的属性中的第一项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have quiz fixtures that have a property called questions, which is an array of ids of associated questions. I want to create a computed property on the model called firstQ that returns the first id in the questions array. Ultimately I would like to take that id and use it to link to a question route I have created.

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

I can not figure out though, how to access that first id in the questions array. Is this even the best way to approach this? Please help.

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 }
    ]
  }
]


推荐答案

好的,所以我找出如何通过模型上的计算属性来执行此操作。这是App.Quiz模型的更新代码:

Okay, so I figured out how to to do this via the computed property on the model. Here's the updated code for the App.Quiz model:

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')
});

这篇关于在Ember.js中,如何创建一个计算属性,该属性引用包含数组的属性中的第一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆