【发布时间】:2014-10-26 05:06:10
【问题描述】:
我正在尝试将属性设置为模型的 async、hasMany 关系的值。但我无法在 then 函数中返回任何值。
App.Athlete = DS.Model.extend({
name: DS.attr('string'),
age: DS.attr('number'),
splits: DS.hasMany('split', {async: true}),
times: DS.hasMany('time', {async: true}),
});
App.Time = DS.Model.extend({
athlete: DS.belongsTo('athlete', {async:true}),
race: DS.belongsTo('race', {async: true}),
time: DS.attr('string'),
});
App.Split = DS.Model.extend({
distance: DS.attr('string'),
time: DS.attr('string'),
athlete: DS.belongsTo('athlete', {async:true}),
race: DS.belongsTo('race', {async: true}),
});
我的问题在于 Athlete 的 ObjectController,我试图将 Time hasMany 数组设置为属性。在then 回调函数之外,我能够正常返回值。但是,在then 回调中,所有值都不会返回undefined/。此外,使用console.log,我始终能够看到代码正在执行。
这是那个方法:
time: function() {
var raceid= '1';
this.get('times').then(function(times) { // returns undefined in this scope
console.log(times.get('length')); // consistently displays
times.forEach(function(time) {
time.get('race').then(function(timerace) {
if(timerace.get('id')===raceid) {
console.log('match'); // consistently diplays
console.log(time.get('time')); // consistently displays
return time.get('time'); // returns undefined/not at all
}
});
});
});
}.property('time.@each.time'),
虽然上面的函数总是返回undefined,但下面的函数(同一个控制器的一部分)可以始终如一地工作而不会出错。
sortedSplits: function(){
var self = this,
raceid = '1',
splits = this.get('splits');
// filter each split by race
this.get('splits').filter(function(split) {
// retrieve race split belongsTo
split.get('race').then(function(race) {
// compare race
return race.get('id') === thisrace;
});
});
splits = splits.sortBy('m');
return splits; // returns correctly
}.property('splits.@each.m'),
看了 6 个小时,我已经不知道该去哪里找问题了。我不明白这个问题是从哪里来的。其他人会碰巧知道这个问题可能出自哪里吗?
注意:我的问题与Computed property in Ember based on async data 的问题类似,尽管我对那个解决方案没有任何运气。
【问题讨论】:
标签: javascript ember.js ember-data indexeddb