2014-02-28 42 views
5

我試圖使用基於來自異步,hasMany模型屬性值的計算屬性,但無法讓它顯示在我的視圖中。基於異步數據的Ember中的計算屬性

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: '[email protected]' }, 
    { id: 2, name: 'mypeep2', email: '[email protected]' } 

]; 

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()」中取出,它就可以工作 - 但是真正的數據是空的,因爲它是作爲異步返回的。如果我儘量做到不異步,我得到

遺漏的類型錯誤:未定義

無法調用「解析」我已經(使用@each,嘗試使用計算的屬性代碼的許多變種model.peeps - 所有這些都正確地顯示了console.log()中的數據,但不是在視圖中。在視圖中,除非我只是將dummy數據返回到then()外 - 否則它將始終未定義) -

我錯過了什麼?

回答

8

不要把hasMany關係視爲承諾,將其視爲數組。這是DS.PromiseArray的整點。如果你只是想要用戶,甚至不打擾計算的屬性,只需在你的模板中使用peeps。但是,如果您需要以某種方式轉換數據,請使用map

showPeeps: function() { 
    return this.get('peeps').map(function(peep) { 
     return { name: peep.name, email: peep.email }; 
    }); 
}.property('[email protected]') 

另外,不要看[]財產。只有在向陣列中添加或刪除項目時纔會更新。你的數組內容不會改變,內容的內容正在改變。您應該觀看@each屬性。您也不需要將[]添加到屬性名稱的末尾,並且不需要將屬性前綴content.

+0

這是我第一次嘗試。這也讓我:「未捕獲TypeError:無法調用未定義的方法」解決「 –

+0

更改異步回到真使這項工作。公認。 –

+1

需要'。@ each'位。謝謝! –