2014-02-23 63 views
0

我試圖從服務器獲取get請求通過REST返回的對象的簡單計數在另一個控制器使用Ember.jsEmber.js計算從商店

爲此屬性我需要做的對服務器的額外請求。基本上這是我的代碼,它幾乎可以工作..但還不完全。也許有人可以找出原因。

它返回一個PromiseArray,這就是爲什麼我使用.then()來訪問屬性。

App.TestController = Ember.ObjectController.extend({ 
    totalCount: function() { 
     return this.store.find('question', {test: this.get('id')}).then(function(items) { 
      var count = items.get('content').get('length'); 
      console.log(count); // This actually logs correct values 
      return count; 
     }) 
    }.property('question') 
}) 

它做什麼它該做的和我越來越)在執行console.log(打印出正確的價值觀,但是當我嘗試在視圖模板中使用{{totalCount}}我越來越[object Object],而不是一個整數。

另外,我是否正確觀察questions屬性?如果該值在其正確的控制器中更改,值會更新?

感謝

+0

的[在灰燼渲染解決承諾值車把模板]可能重複(http://stackoverflow.com/questions/20623027/rendering -resolved-promise-value-in-ember-handlebars-template) – aemxdp

回答

8

你所看到的問題是,因爲你正在返回一個承諾的財產和車把的值不會評估你的承諾。你需要做的是創建一個單獨的函數,觀察question,然後在那裏調用你的商店來更新totalCount屬性。這將是這樣的。

App.TestController = Ember.ObjectController.extend({ 
    totalCount: 0, 
    totalCountUpdate: function() { 
     var that = this; 
     this.store.find('question', {test: this.get('id')}).then(function(items)  { 
      var count = items.get('content').get('length'); 
      console.log(count); 
      that.set('totalCount', count); 
     }) 
    }.observes('question') 
}) 
+0

謝謝你,卡爾 - 約翰!這實際上是有道理的。但是,儘管console.log輸出了所需的值,但該視圖仍然沒有得到更新事件。我觀察正確的財產?我是否需要隱式調用totalCountUpdate?在我看來,我仍然在使用{{totalCount}},但它被卡在了0. – kernelpanic

+0

讓我覺得我可能應該觀察totalCount屬性?因爲它是一個變化.. – kernelpanic

+0

該視圖將自動創建totalCount觀察員。上面的代碼看起來很好。當問題改變時,totalCountUpdate將會被調用,然後調用set the totalCount,這會觸發UI應該響應的屬性更改通知。你能添加一個jsbin來重現這個問題嗎? –

1

或者totalCount可能懶洋洋地爲自己,是這樣的:

App.TestController = Ember.ObjectController.extend({ 
    totalCount: 0, 
    question: // evaluate to something, 
    totalCount: function() { 
     var that = this; 
     that.store.find('question', {test: that.get('id')}).then(function(items)  { 
      var count = items.get('content').get('length'); 
      that.set('totalCount', count); 
     }) 
    }.observes('question').property() 
})