In Ember.js how do I create a computed property that references first item in property containing an array

限于喜欢 提交于 2019-12-11 14:57:15

问题


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.

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

回答1:


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



回答2:


You can use the firstObject property of Ember Arrays to create a binding between firstQ and the first Id in questions array. Define your firstQ property as a binding like this

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


来源:https://stackoverflow.com/questions/22494140/in-ember-js-how-do-i-create-a-computed-property-that-references-first-item-in-pr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!