3
votes

I'm attempting to build a non blocking async call in an Ember.js app without using Ember Data.

I have the following Ember.js model:

App.Player = Ember.Object.extend({
    id: '',
    alias: '',
    name: '',
    twitterUserName: '',
    isFeatured: ''
});

App.Player.reopenClass({
    getPlayers: function () {
        var players = Ember.ArrayProxy.create({ content: [] });
        $.getJSON("/api/players").then(function (response) {
            response.forEach(function (p) {
                players.pushObject(App.Player.create(p));
            });
        });
        return players;
    }
});

And I am calling it as follows in my route:

App.IndexRoute = Ember.Route.extend({
    model: function (params) {
        return App.Player.getPlayers();
    }
});

For some reason I am getting the following javascript error:

Uncaught TypeError: Object # has no method 'forEach'

I've tried a few variants I have seen around but nothing seems to work. Any help would be appreciated...

EDIT - Found the solution with some help from Darshan, here's the working code:

App.Player.reopenClass({
    getPlayers: function () {
        var players = [];
        $.ajax({
            url: "/api/players",
        }).then(function (response) {
            response.players.forEach(function (player) {
                var model = App.Player.create(player);
                players.addObject(model);
            });
        });
        return players;
    }
});
1

1 Answers

4
votes

Your response.forEach suggests that you are expecting the json response body to be an array. It is probably wrapped in some root element like players or data like so.

{
  "players": [...]
}

If that is the case you need to use forEach on that root element like response.players.forEach.

You also want to restructure that code to return a promise directly. The Ember router will then pause until your json is loaded and only proceed after it finishes. Something like this,

getPlayers: function () {
  return $.getJSON("/api/players").then(function (response) {
    var players = Ember.ArrayProxy.create({ content: [] });
    response.players.forEach(function (p) {
      players.pushObject(App.Player.create(p));
    });

    return players;
  });
}

Returning players resolve the promise. And Ember understands that when a promise resolves that result is the model.