我正在尝试使用基于来自 async、hasMany 模型属性的值的计算属性,但无法将其显示在我的 View 中。
MyApp.Foo = DS.Model.extend({
title: DS.attr('string'),
peeps: DS.hasMany('peep', { async: true });
});
MyApp.Peep = DS.Model.extend({
name: DS.attr('string'),
email: DS.attr('string')
});
MyApp.Foo.FIXTURES = [
{ id: 1, title: 'nice', peeps: [1,2] }
];
MyApp.Peep.FIXTURES = [
{ id: 1, name: 'mypeep', email: 'peep@example.com' },
{ id: 2, name: 'mypeep2', email: 'peep2@example.com' }
];
MyApp.FooController = EmberObjectController.extend({
showPeeps: function() {
// This one works for this test data.
// return [{name: 'baz', email: 'bar'}];
var peepList = this.get('content.peeps.[]').then(function(c) {
// This one does not work, even for this test data.
return {name: 'baz', email: 'bar'}];
});
}.property('content.peeps.[]');
});
在我看来,大致如下:
{#each peep in controller.showPeeps}}{{peep.name}}{{/each}}
我可以使用console.log()查看“then()”中的所有数据,并且正如代码注释中所指示的那样,如果我从“then()”中取出返回值,它就可以工作 - 但随后是真实数据为空,因为它作为异步返回。如果我尝试使其非异步,我会得到
未捕获的类型错误:无法调用未定义的方法“解析”
我已经尝试了许多计算属性代码的变体(使用 @each,使用 model.peeps - 所有这些都在 console.log() 中正确显示数据,但不在 View 中。在 View 中,它总是未定义的,除非我只是在 then() 之外返回虚拟数据 - 显示正确)
我错过了什么?
最佳答案
不要把 hasMany 关系当作一个 promise,把它当作一个数组。这就是DS.PromiseArray
的全部意义.如果你只想要用户,甚至不要理会计算属性,只需使用 peeps
在您的模板中。但是,如果您需要以某种方式转换数据,请使用 map
.
showPeeps: function() {
return this.get('peeps').map(function(peep) {
return { name: peep.name, email: peep.email };
});
}.property('peeps.@each')
另外,不要看
[]
属性(property)。只有在从数组中添加或删除项目时才会更新。您的数组内容没有改变,内容的内容正在改变。你应该看 @each
属性(property)代替。您也不需要添加 []
到属性名称的末尾,并且您不需要在属性前面加上 content.
.
关于asynchronous - Ember 中基于异步数据的计算属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22088746/