【问题标题】:Computed property in Ember based on async dataEmber 中基于异步数据的计算属性
【发布时间】:2014-04-01 01:50:12
【问题描述】:

我正在尝试使用基于 async、hasMany 模型属性的值的计算属性,但无法让它显示在我的视图中。

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()”中的所有数据,正如代码 cmets 中所指出的,如果我从“then()”中取出返回值,它就可以工作 - 但随后真实数据是空的,因为它是异步返回的。如果我尝试使其非异步,我会得到 ​​p>

未捕获的类型错误:无法调用未定义的“解决”方法

我尝试了许多计算属性代码的变体(使用@each,使用model.peeps - 所有这些都正确显示console.log()中的数据,但不在视图中。在视图中,它是总是未定义,除非我只是在 then() 之外返回虚拟数据 - 显示正确)

我错过了什么?

【问题讨论】:

    标签: asynchronous ember.js


    【解决方案1】:

    不要把 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')
    

    另外,不要观看[] 属性。仅当从数组中添加或删除项目时才会更新。您的数组内容没有改变,内容的内容正在改变。您应该注意 @each 属性。您也不需要在属性名称的末尾添加[],也不需要在属性前面加上content.

    【讨论】:

    • 这是我尝试的第一件事。这也让我明白:“未捕获的 TypeError:无法调用未定义的方法 'resolve'”
    • 将 async 改回 true 使这项工作有效。接受。
    • 需要.@each 位。谢谢!
    • 请注意那些编写规范的人:我发现在为涉及异步关系的计算属性编写测试时,我需要两次获取下游计算属性。第一个触发 ajax 请求,下一个将读取正确的值(等待异步请求完成)。
    猜你喜欢
    • 1970-01-01
    • 2014-01-07
    • 2014-07-14
    • 2015-04-28
    • 2014-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-26
    相关资源
    最近更新 更多