Ember.js 如何在第一次在Ember中访问关联记录时加载它们?
我有一个computed属性,它获取一个关联的记录并尝试打印它。我第一次提取记录时,它是空的。所有后续访问都正常工作。它被设置为“async:true”,但将其设置为false不会改变此行为Ember.js 如何在第一次在Ember中访问关联记录时加载它们?,ember.js,Ember.js,我有一个computed属性,它获取一个关联的记录并尝试打印它。我第一次提取记录时,它是空的。所有后续访问都正常工作。它被设置为“async:true”,但将其设置为false不会改变此行为 MyApp.ThingsController = Ember.ArrayController.extend({ myProperty: function() { var content = this.get('content'); return content.f
MyApp.ThingsController = Ember.ArrayController.extend({
myProperty: function() {
var content = this.get('content');
return content.filter(function(thing) {
console.log(thing.get('title')); // Since this is a direct attribute on the model, it prints fine.
var associatedThing = thing.get('associatedThing'), otherThings = [];
console.log(associatedThing.get('content')); // This is a hasMany attribute on the model, and is null the *first* time, but fine on subsequent accesses.
otherThings = associatedThing.get('content'); // Obviously doesn't work the first time either.
return thing.get('title') + otherThings[0].get('name'); // Or similar.
});
}.property('content.@each') // adding observers for content.associatedThing.@each does not seem to make any difference.
});
模型如下:
MyApp.Thing = DS.Model.extend({
title: DS.attr('string'),
associatedThings: DS.hasMany('associatedThing', { async: true })
});
MyApp.AssociatedThing = DS.Model.extend({
name: DS.attr('string')
});
显然,我不能在这里使用承诺,因为我需要从函数返回一个值,所以我不能使用回调,因为我们在计算属性中。如何在第一次访问此关联记录时使其工作
编辑:myProperty是ArrayController上的计算属性,用于显示或隐藏内容事实上,您可以使用承诺,但不是您的思维方式。对于许多关系,余烬数据返回一个。这意味着它返回一个将解析为数组的承诺。但同时,代理将实际响应您使用未定义的get请求。然后,当承诺达成时,任何观察者都会被解雇。因此,如果您的属性依赖于associatedThings属性,它将在承诺解析时更新。换言之,这将按预期工作:
MyApp.Thing = DS.Model.extend({
title: DS.attr('string'),
associatedThings: DS.hasMany('associatedThing', { async: true }),
sum: function() {
var things = this.get('associatedThings');
return things.filter(function(thing) {
return shouldFilterThing(thing);
});
}.property('associatedThings.@each.size')
});
另外,请不要被这不是同步发生的事实所困扰。尝试将其从异步更改为同步只会使代码更加脆弱。让Ember完成它的工作,并为您处理所有属性和绑定。我的解决方案就是访问ArrayController的init方法中的关联数据:
init: function() {
var content = this.get('content');
content.forEach(thing) {
// Prime the data.
var associatedThings = get('associatedThings');
});
}
这使一切都按预期进行。谢谢您的回复。我在原来的帖子中添加了额外的信息,以澄清我试图做的事情。我将我的属性放在模型中,但它也可以很容易地放在ArrayController中。同样的概念也适用。观看你想要的属性,余烬将确保它们在需要时得到更新。嗯,不为我工作。它在第一次仍然为空,并且在随后的一次中出现。