Wasim
Wasim

Reputation: 5113

Ember.js - Ember Data not returning a model

I'm using Ember Data to retrieve a playlist with songs. The code is:

App.PlaylistRoute = Em.Route.extend({
    model: function(params) {
        var plist = this.store.find('playlist', params.id);
        console.log(plist);
        return [];
    }
})

App.Playlist = DS.Model.extend({
    beats: DS.hasMany('beat')
});

App.Beat = DS.Model.extend({
    name: DS.attr('string') 
});

The problem with this code is that it works and returns data but in an obscure object, not in a model. I cannot then do plist.get('beats') or plist.get('id') as it just returns undefined. The JSON data is really simple:

{
    "playlist": {
        "id": "popular-beats",
        "beats": [
            "1",
            "2"
        ]
    },
    "beats": [
        {
            "id": "1",
            "name": "Name"
        },
        {
            "id": "2",
            "name": "Another Name"
        }
    ]
}

When I log the array in the console, here is the object that is returned:

__ember1383247403867: "ember293"
__ember1383247403867_meta: e
_super: undefined
content: s
isFulfilled: true
toString: function (){return e}
__proto__: Object

If I drill down into content._data I will find the beats array - so data is loaded successfully, but it's not returning a proper model that I am expecting.

Upvotes: 1

Views: 1632

Answers (1)

Anton Lantsov
Anton Lantsov

Reputation: 336

store.find() does not return model object immediately, it returns promise, that will contain 'beats' and 'id' properties in the future. so you can use model in templates, and templates will be updated when model updated.

http://emberjs.jsbin.com/oTEvIwe/3 - this is an ember application based on your router and models. in console, you can see that plist.get('beats') is undefined in router#model, but html page contains it.

if you want manipulate with model in router you can use setupController.

http://emberjs.jsbin.com/oTEvIwe/3/edit - source.

more about promises - http://emberjs.com/guides/routing/asynchronous-routing/

Upvotes: 2

Related Questions