Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember.js: Proper way to cast Em.$.getJSON into a promise and bind response to controller context?

I'm fetching some data with $.getJSON that I want to asynchronously bind to controller context. I've come up with this in my route - which works, but I'm not happy with it:

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

Then, in my template, I can, for example, use:

Foo: {{matchdayStats.foo}}

And it works just fine. Is there a better way to write this (perhaps without promise casts and Em.Object creation) - I know this automatically works if I put Em.$.getJSON into a model hook.

like image 729
Matic Jurglič Avatar asked Apr 02 '15 19:04

Matic Jurglič


1 Answers

You could use a DS.PromiseObject

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

controller.set('matchdayStats', matchdayStats);

This is the way Ember Data accesses/displays related objects and the properties of those objects in templates.

like image 121
jmurphyau Avatar answered Sep 23 '22 06:09

jmurphyau