2014-01-22 116 views
0

我一直試圖在一個視圖中顯示兩個模型。這裏是我的代碼:模板骨幹中的兩個模型查看

var self=this; 
var aboutus=new Aboutus({id:1}); 
var company= new Company({id:1}); 
aboutus.fetch(); 
company.fetch(); 


var model = new Backbone.Model(); 
model.set({aboutus: aboutus, company: company}); 
var aboutusView=new AboutusView({model:aboutus,model2:company}); 
aboutusView.render(); 
self.changePage(aboutusView); 


======================= 

For Aboutus View Part: 


var AboutusView = Backbone.View.extend({ 

template: _.template(aboutusViewTemplate), 

initialize: function() { 
    _.bindAll(this, 'render'); 

}, 


render: function(){ 

console.log(this.model); 
console.log(this.options.model2); 


this.$el.html(this.template(this.model.toJSON())); 

    return this; 
} 
}); 

return AboutusView; 




============================ 
In console log of this.model (aboutus) is: 
=========================== 
child {attributes: Object, _escapedAttributes: Object, cid: "c0", changed: Object,  _silent: Object…} 
_changing: false 
_escapedAttributes: Object 
_pending: Object 
_previousAttributes: Object 
_silent: Object 
    attributes: Object 
    aboutusId: 1 
    description: "testing" 
     id: 1 
     imageExtension: "" 
     title: "ABOUT US" 
__proto__: Object 
changed: Object 
    cid: "c0" 
    id: 1 
__proto__: ctor 

所以,問題是我想顯示關於我們的aboutusId屬性,例如,描述:

在路由器本部獲取的機型關於我們和公司,並將它們添加到AboutusView 。我怎樣才能做到這一點?

+0

哪裏是aboutusViewTemplate – 2014-01-22 13:05:27

+0

@eguneys aboutusViewTemplate的定義僅僅是HTML模板展示數據。 – JaRoi

回答

1

而不是發送this.model.toJSON()到您的模板,發送這兩個數據集(模型)。請記住,您可以將任何類型的JSON對象發送到模板。你可以這樣做:

var somedata = { 
    aboutus: this.model.toJSON(), 
    company: this.options.model2.toJSON() //or 'this.model2.toJSON()', not completely sure where this model is accessible in the view. 
    } 

this.$el.html(this.template(somedata)); 

然後在你的模板中,您可以通過<%= aboutus.description %><%=company.id %>(例如)訪問每個模型。

+0

其實this.model不是模型它正在返回的孩子(如上所示)有關如何檢索兒童內部屬性的任何想法 – JaRoi

+0

哦,我明白了。我在下面添加了一個新答案。希望有幫助。 –

0
var model = new Backbone.Model(); 
model.set({aboutus: aboutus, company: company}); 
var aboutusView=new AboutusView({model:aboutus,model2:company}); 

在上面這幾行,創建了var model但絕不添加附加modelAboutusView。難道你想做的事:

var aboutusView=new AboutusView({model:model}); 

這樣做,你現在有一個模型,稱爲model具有屬性aboutuscompany,您可以通過在你的模板傳遞model.toJSON()在你的模板訪問。

如果公司簡介和公司也模型(我假定他們是),你可以訪問你的觀點它們的屬性:

this.model.get('aboutus').get('id')