Pregunta

I have the following user object returned from a REST Api:

{
    user: {
        id: 3451,
        name: "First Last",
        favorites: {
            designs: {
                name: "Design 1",
                url: "Url 1"
            },
            typo: {
                name: "Typo 1",
                url: "Url 2"
            },
            games: {
                name: "Game 1",
                url: "Url 3"
            }
        }
    }
}

I got this response from the url /users/3451.

And here's my User model:

App.User = DS.Model.extend({
    name: DS.attr('string'),
    favorites: DS.attr(), // ??? What to put here?
});

I have no problem displaying the {{name}}. But in the favorites, I don't know. I tried using {{#each}}

{{#each favorites}}
    {{@key}} - {{name}}
{{/each}}

but no luck.It throws an error: Error: Assertion Failed: The value that #each loops over must be an Array. You passed [object Object]

What is the correct way of handling these kinds of complex objects in EmberJS? Please help.

¿Fue útil?

Solución

I think the error is pretty self explanatory: you need to be looping over an array, not an object. Here's how I would convert that object to an array, while saving the key (put this in your model):

favoritesArray: function() {
    var favorites = this.get('favorites');
    return Em.keys(favorites).map(function(key) {
        return {
            key: key,
            data: favorites[key]
        };
    });
}.property('favorites.@each.{name,url}')

Then, in your template:

{{#each favoritesArray}}
    {{key}} - {{data.name}}
{{/each}}

That would be the easiest way to do it. But if you're looking for a slightly better way (in my opinion), you can user a type transform to convert the data to the format you need at the time of (de)serialization.

EDIT: Just for a bit of background info, I believe the reason that Ember.js doesn't support iterating over objects is because there is no way to bind to the object keys. Ember.js knows to update a bound helper when the dependent key observers are fired, but as far as I know, there is no way to observe the keys of an object. Something like this might be possible using an Map or similar, but I don't think that it's built in functionality.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top