![](/img/trans.png)
[英]Ember controller not refreshing template after setting property in promise
[英]Ember Controller Property, Promise, and Scope
我对Javascript非常陌生,甚至对Ember都比较陌生,我有一个异步hasMany关联,我试图在父模型控制器中求和子模型(锦标赛)的属性。 我对函数范围的理解是内部函数将可以访问包含函数中的所有内容(除此以外),到目前为止还可以。 我正在尝试在诺言解决时增加金额,但是它必须使新的金额变量变大,因为一旦我将其返回到外部forEach,它又回到了0,而且我不确定我要去哪里错误。 我知道我没有在.property()中设置依赖项,我只是想首先解决这个问题。
totalPrice: function(){
var self = this;
var allTourn = this.get('model.tournaments');
var amount = 0;
allTourn.forEach(function(tournament){
var tID = Number(tournament.get('id'));
self.store.find('tournament', tID).then(function(value){
amount += Number(value.get('buyIn'));
//amount is set to the buyIn property as expected
})
// amount is 0 out here... shouldnt the amount in the promise be using the outter amount variable?
});
return amount; // == 0
}.property()
基于托尼的答案的解决方案,我将其移至该路线,并在routes / package.js视图中解决了承诺问题
export default Ember.Route.extend({
model: function(params) {
return this.store.find('package', params.package_id);
},
setupController: function(controller, model){
var allTourn = model.get('tournaments');
var self = this;
var totalPricePromise = new Ember.RSVP.Promise(function(resolve, reject) {
var tournyPromises = allTourn.map( function(tournament){
var tID = Number(tournament.get('id'));
return self.store.find('tournament', tID)
});
Ember.RSVP.all(tournyPromises).then(function(tournamentList){
var amount = 0;
tournamentList.forEach(function(tournament){
amount += Number(tournament.get('buyIn'));
})
resolve(amount);
controller.set('totalPrice', amount);
});
});
controller.set('package', model);
}
});
就像eggward在评论中说的那样,totalPrice是在不等待store.find()承诺的情况下返回的金额。 在总价格完成后的某个时间,将承诺排队等待稍后运行。
因此,如果必须等待promise进行计算,则可以从totalPrice返回promise,并在所有store.find()调用完成后对其进行解析。 您可以使用Ember promises的all()方法对发现进行分组。 例如,您可以尝试如下操作,而不是allTourn.forEach:
// create a promise to return from totalPrice()
var totalPricePromise = new Ember.RSVP.Promise(function(resolve, reject) {
// create an array of promises from the find() calls.
var tournyPromises = allTourn.map( function(tournament){
var tID = Number(tournament.get('id'));
return self.store.find('tournament', tID)
});
// user RSVP.all to wait for all the finds to complete
// it automatically groups all the results into an array
Ember.RSVP.all(tournyPromises).then(function(tournamentList){
var amount = 0;
tournamentList.forEach(tournament){
amount += Number(tournament.get('buyIn'));
})
// this resolve is from the Ember.RSVP.Promise at the top
// it will finally get to whoever called totalPrice()
resolve(amount);
});
// return the promise from totalPrice, instead of the amount
return totalPricePromise;
});
但是,如果您例如在车把帮手中需要诺言,则诺言作为财产可能无法很好地发挥作用。 作为一种替代方法,您可以将所有的Promise东西移动到设置模型的路线上,以便在控制器中您已经拥有所有的锦标赛。 然后,您不必等待totalPrice函数中的find()操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.