2013-12-13 102 views
0

型號代碼:Backbone:如何從另一個模型中的集合中獲取模型屬性?

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

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

查看:

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); 
    } 

我在var historyRow = JST['teaminfo/history/row'] (historyData.attributes);線越來越"Uncaught TypeError: Cannot read property 'attributes' of undefined"

在我定義historyData時出現問題之前,可能是因爲它是另一個模型(app.currentTeam)的集合中的模型(app.currentTeam.attributes.history)。我得到了[Object] (app.currentTeam.attributes.history) doesn't have a 'get' method類型的錯誤。現在它傳遞良好,但在下一行中我收到了另一個錯誤消息,所以我想知道我的代碼在這裏出了什麼問題。

app.currentTeam.attributes加載罰款,所以我想有檢索模型是另一個模型中的集合內的屬性的問題。

編輯:團隊和歷史收集的關係:

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

請出示團隊和歷史收藏 – Sergey

+0

的關係@Sergey我加了關係。 –

+0

爲什麼你使用attributes.history而不是get('history')? – Sergey

回答

1

您的收藏從錯誤的方法獲得型號

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

你必須使用

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

UPDATE1: 嘗試使用迭代器獲取ele從收集發言::

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); 
+0

謝謝,我改變了代碼,但我仍然得到相同的錯誤。我不知道還有什麼可以導致它。 –

+0

你現在有的代碼? – Sergey

+0

你在JavaScript的調試器中調試你的應用程序嗎? Chrome開發工具或FireBug? – Sergey

相關問題