所以我是 Ember 的新手,并试图找出设置依赖于相关模型数据的计算属性的最佳方法。我将包括以下模型仅供引用。
我想将计算属性设置为异步结果 (desiredOutcome)。
我的问题 我这是怎么了?或者使用观察者更合适,就像在这个 question 中一样.
score: function() {
var self = this;
var allscores = this.get('model.scores');
//Find the scoreRecord that has the appropriate objective id (in this case just 1)
var scoreRecord = allscores.find(function(item){
var scoreID = item.get('id');
return self.store.find('score', scoreID).then(function(scoreRecord){
var objID = Number(scoreRecord.get('objective.id'));
if (objID === 1){return true;}
});
});
//Return the scoreRecord's score attribute
var scoreID = scoreRecord.get('id');
return this.store.find('score', scoreID).then(function(score){
var desiredOutcome = score.get('score');
console.log(desiredOutcome);
return desiredOutcome;
});
}.property('model.@each.scores', 'selectedObjective'),
为变量名称等选择不当而道歉......
我的模型:
学生
scores: DS.hasMany('score', {async: true}),
name: DS.attr('string')
目标
name: DS.attr('string'),
scores: DS.hasMany('score', {async : true})
评分
scoreResult: DS.attr('number'),
objective: DS.belongsTo('objective', {async: true}),
student: DS.belongsTo('student', {async: true})
------------- 更新 ---------------
JSBin here .所以我想要的是返回其中一个分数,即记录在控制台中的 1 或 2,作为计算属性“分数”。但我假设我只是在返回一个 Unresolved promise - 对 promise 缺乏经验 - 我如何适应才能解决?
——我也一直在想,对我在这里尝试做的事情采取不同的方法可能会更好。我可能会考虑使用适当的“分数”模型创建一个组件。如果可行,我会更新一些细节。
最佳答案
当我今天在同样的事情上挣扎时,答案似乎是使用 DS.PromiseObject
.
所以首先你把它包括在内:
import DS from 'ember-data';
然后你创建你的计算属性,如:
property: Ember.computed('id', function(){
return DS.PromiseObject.create({
promise: this.get('store').findRecord('account', this.get('id')).then((data) => {
return 'Mr. ' + data.get('name');
})
});
})
最后在您的模板中,您可以使用 访问结果内容 (这是捕获):
{{property.content}}
这就是全部:) 在这种特殊情况下,当您更改 Id 时,它将解析并显示一个新名称。
关于ember.js - Ember - 异步计算属性或观察者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28744882/