2013-06-21 33 views
5

更新Ember JS數組未反映在視圖中。Ember JS,更新未在視圖中反映的數組

控制器

App.MyController = Ember.ArrayController.extend({ 
    results: [], 
    init: function(){ 
    _this = this 
    App.MyModel.find({}).then(function(contents) { 
     obj1 = contents.objectAt(0) 
     obj1.get('data').hasMany.results.forEach(function(item){ 
      _this.results.push(item) 
     }); 
    }) 
    //rest of the code 
    } 
}) 

模板

{{#each results}} 
    // show items of reults. 
{{/each}} 

這是一塊在其中我是從服務器中獲取數據的代碼,並且在它的加載,我將其推入結果的數組。 從服務器加載數據需要一些時間,所以模板映射到空結果數組上。理想情況下,結果數組應該更新模板中的東西,但在邏輯上它不應該。

有沒有人知道我失蹤的地方?或做錯了。

在此先感謝。

回答

15

對於綁定工作,您必須使用pushObject而不是push。燼陣列pushObject

App.MyController = Ember.ArrayController.extend({ 
    results: [], 
    init: function(){ 
    _this = this; 
    App.MyModel.find({}).then(function(contents) { 
     obj1 = contents.objectAt(0); 
     obj1.get('data').hasMany.results.forEach(function(item){ 
     _this.results.pushObject(item) 
     }); 
    }) 
    //rest of the code 
    } 
}); 

富勒更多信息,請參閱here

希望它有幫助。

+0

你剛剛救了我的一天。謝謝你,兄弟。 –

+0

請注意,您的數組需要是'Ember.NativeArray',它也是'MutableArray'。如果你有擴展原生js數組原型的燼,那麼原生js數組將具有'.pushObject(thing)'函數。如果你不擴展本地原型,你將需要使用'Ember.A([])'。 [更多關於Ember.A()](https://emberjs.com/api/ember/3.0/functions/@ember%2Farray/A) –

0

我有類似的問題。問題是Ember沒有得到有關陣列變化的通知。在這種情況下,你有一個特殊的Ember函數(pushObject),它取代了標準的Push,並通知了框架的變化。但在其他情況下(例如Array.splice),您沒有這樣的功能,所以您需要手動通知框架。你可以這樣做:

this.notifyPropertyChange('array'); 
相關問題