基于异步数据灰烬计算属性 [英] Computed property in Ember based on async data
问题描述
我试图用基于从异步,的hasMany模型属性值的计算的属性,但不能让它在我的视图中显示。
I'm trying to use a computed property based on the values from an async, hasMany model property, but cannot get it to display in my 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.[]');
});
在我看来,沿着线的东西:
In my view, something along the lines of:
{#each peep in controller.showPeeps}}{{peep.name}}{{/each}}
我可以看到所有数据,那么()使用的console.log(),并表示在code注释,它的工作原理,如果我走了回报的,那么() - 因为它是返回为异步但实际数据是空的。如果我尽量做到不异步,我得到
I can see all the data in the "then()" using console.log(), and as it indicates in the code comments, it works if I take the return out of the "then()" - but then the real data is empty because it is returned as async. If I try to make it non-async, I get
的未捕获类型错误:不能调用方法解析未定义的
我试过计算财产code的许多变种(使用@each,使用model.peeps - 所有这一切都正确显示的console.log数据(),但不是在视图在视图,它始终是不确定的,除非我刚刚回到外面的虚拟数据则() - 它正确地显示)
I've tried many variants of the computed property code (using @each, using model.peeps - all of which correctly show the data in console.log(), but not in the view. In the view, it is always undefined unless I just return dummy data outside of the then() - which displays correctly)
我是什么失踪?
推荐答案
不要把作为一个诺言的hasMany关系,把它当作一个数组。这就是 DS.PromiseArray
整点。如果你只是想用户,甚至不与计算财产打扰,只需要使用一瞥
在模板中。但是,如果你需要将数据转换成某种方式,使用地图
。
Don't treat the hasMany relationship as a promise, treat it as an array. That's the whole point of DS.PromiseArray
. If you just want the users, don't even bother with the computed property, just use peeps
in your template. But, if you need to convert the data somehow, use map
.
showPeeps: function() {
return this.get('peeps').map(function(peep) {
return { name: peep.name, email: peep.email };
});
}.property('peeps.@each')
另外,不看 []
属性。只有当一个项目被添加或从数组中删除更新。阵列内容不被改变,内容的内容被改变。你应该看 @each
属性。你也不需要添加 []
属性名称的末尾,你不需要preFIX与内容。
。
Also, don't watch the []
property. That only updates when an item is added or removed from the array. Your array contents aren't changing, the contents of the contents are changing. You should watch the @each
property instead. You also don't need to add []
to the end of the property name, and you don't need to prefix the property with content.
.
这篇关于基于异步数据灰烬计算属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!