2015-04-02 9 views
7

我正在使用$ .getJSON獲取一些數據,我想異步綁定到控制器上下文。我想出了這個在我的路線 - 它的工作原理,但我不喜歡它:

setupController: function(controller, model) { 
    this._super(controller, model); 
    Em.RSVP.Promise.cast(Em.$.getJSON((this.get('ENV.apiBaseURL')) + "https://stackoverflow.com/users/current/live_matchday_stats")).then((function(_this) { 
    return function(s) { 
    return _this.controller.set('matchdayStats', Em.Object.create(s)); 
    }; 
} 

然後,在我的模板,我可以,例如,使用:

Foo: {{matchdayStats.foo}} 

它工作得很好。有沒有更好的方法來寫這個(也許沒有承諾轉換和Em.Object創建) - 我知道這會自動工作,如果我把Em。$。getJSON放入模型鉤子。

+0

'Em。$。getJSON()'方法默認返回一個Promise,不需要轉換。由於Ember計劃[遠離控制器](http://discuss.emberjs.com/t/ember-2-0-moving-away-from-controllers/6728),您應該將其添加到Route的'模型'鉤子。任何你不是的原因? – trentmwillis 2015-04-02 21:37:26

+0

因爲我的模型是別的東西,而且這個數據只是與模型無關的東西,但我仍然需要加載它並在模板中顯示。 – 2015-04-03 07:25:40

回答

1

你可以使用一個DS.PromiseObject

var matchdayStats = DS.PromiseObject.create({ 
    promise: Em.$.getJSON((this.get('ENV.apiBaseURL')) + "https://stackoverflow.com/users/current/live_matchday_stats") 
}); 

controller.set('matchdayStats', matchdayStats); 

這是灰燼的數據訪問方式/顯示器相關的對象和模板中的這些對象的屬性。

+0

我不想用它作爲模型,因爲我的模型已經是別的東西了。 – 2015-04-03 07:24:43

+0

對不起,我會更新我的答案 – jmurphyau 2015-04-03 07:34:21

相關問題