![](/img/trans.png)
[英]How do you create a computed property in Ember.js to see if a single Ember Data attribute is dirty?
[英]In Ember.js how do I create a computed property that references first item in property containing an array
我有一個測驗裝置,它具有一個稱為問題的屬性,它是一組相關問題的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 }
]
}
]
好的,所以我弄清楚了如何通過模型上的計算屬性來執行此操作。 這是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')
});
您可以使用Ember數組的firstObject屬性在firstQ
和questions
數組中的第一個ID之間創建綁定。 將您的firstQ
屬性定義為這樣的綁定
App.Quiz = DS.Model.extend({
name: DS.attr('string'),
description: DS.attr('string'),
questions: DS.hasMany('question', {async: true}),
firstQBinding: 'questions.firstObject'
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.