Search code examples
javascriptbackbone.jsbackbone-relational

Backbone: How to get model attributes from a collection inside another model?


Model code:

App.Team = Backbone.RelationalModel.extend({
urlRoot: 'data/json/team',
/*urlRoot: 'data/json/myteam.txt',*/
idAttribute: 'id',
relations:
...

app.currentTeam = new App.Team({id:11});

View:

var trophiesBox = JST['teaminfo/history/leftbox'](app.currentTeam.attributes);
    $("#teamhistory_leftbox").append(trophiesBox);  
    for (var i = 1; i <= app.currentTeam.attributes.history.length; i++)   { 
        var historyData = app.currentTeam.attributes.history.get(i);
        var historyRow = JST['teaminfo/history/row']    (historyData.attributes);
        $("#teamhistory_table_body").append(historyRow);
    }

I'm getting "Uncaught TypeError: Cannot read property 'attributes' of undefined" on var historyRow = JST['teaminfo/history/row'] (historyData.attributes); line.

Before I had problems defining historyData, probably since it is a model in a collection (app.currentTeam.attributes.history) inside of another model (app.currentTeam). I was getting [Object] (app.currentTeam.attributes.history) doesn't have a 'get' method type of error. Now it passes fine, but I get another error message in the next line, so I wonder what is wrong with my code here.

app.currentTeam.attributes loads fine, so I guess there is a problem retrieving attributes of a model that is inside a collection within another model.

Edit: relation of Team and History collection:

{
    type: Backbone.HasMany,
    key: 'history',
    relatedModel: 'App.HistoryItem',
    collectionType: 'App.History',
    reverseRelation: {
        key: 'team',
        includeInJSON: 'id',
    }
}

Solution

  • You get Model from Collection from wrong method

    app.currentTeam.attributes.history.get(i);
    

    You have to use

    app.currentTeam.get('history') // you got collection
    app.currentTeam.get('history').at(i); // you got model from collection by index
    

    Update1: Try use iterator for get elements from collection:

    var trophiesBox = JST['teaminfo/history/leftbox'](app.currentTeam.attributes);
    $("#teamhistory_leftbox").append(trophiesBox);  
    app.currentTeam.get('history').each(function(historyData, i) {
        var historyRow = JST['teaminfo/history/row'](historyData.attributes);
        $("#teamhistory_table_body").append(historyRow);
    }, this);