2013-07-07 149 views
0

我試圖將集合視圖嵌套到模型視圖中。使用Backbone初始化嵌套集合

爲了做到這一點,我用骨幹木偶複合視圖和followed that tutorial

末了,他初始化像這樣的嵌套集合視圖:

MyApp.addInitializer(function(options){ 
    var heroes = new Heroes(options.heroes); 

    // each hero's villains must be a backbone collection 
    // we initialize them here 
    heroes.each(function(hero){ 
    var villains = hero.get('villains'); 
    var villainCollection = new Villains(villains); 
    hero.set('villains', villainCollection); 
    }); 

    // edited for brevity 

}); 

你會怎樣做同樣的不使用Marionette的addInitalizer?

在我的項目中,我正在從服務器獲取數據。當我嘗試做這樣的事情:

App.candidatures = new App.Collections.Candidatures; 

App.candidatures.fetch({reset: true}).done(function() { 
    App.candidatures.each(function(candidature) { 
     var contacts = candidature.get('contacts'); 
     var contactCollection = new App.Collections.Contacts(contacts); 
     candidature.set('contacts', contactCollection); 
    }); 
    new App.Views.App({collection: App.candidatures}); 


}); 

我得到一個「indefined選項」從收集來:

App.Collections.Contacts = Backbone.Collection.extend({ 
model: App.Models.Contact, 

initialize:function(models, options) { 
    this.candidature = options.candidature; 
}, 


url:function() { 
    return this.candidature.url() + "/contacts"; 
} 
)}; 

回答

0

這是因爲當你創建contactCollection,你不提供candidatures收藏在options對象中。你需要修改您的聯繫人集合初始化代碼是這樣的:

initialize:function(models, options) { 
    this.candidature = options && options.candidature; 
} 

這樣的candidature屬性將被設置爲所提供的值(如果沒有提供,這將是undefined)。

然後,你還需要提供當你instanciating收集的信息:

App.candidatures.each(function(candidature) { 
    var contacts = candidature.get('contacts'); 
    var contactCollection = new App.Collections.Contacts(contacts, { 
     candidature: candidature 
    }); 
    candidature.set('contacts', contactCollection); 
}); 

P.S:我希望你找到我的博客文章有用!

+0

嗨大衛!很高興在這裏得到你的回答!你的文章真的很棒!我知道candidateature.contacts已經設置...但我無法檢索的數據:(即使修改按照您的建議聯繫模式 – user2167526

+0

對不起,我有點誤讀你的代碼。我更新了我的答案。 –

+0

感謝回覆!我想我越來越近(在這一週後!)。但是現在如果在候選人視圖(第一級),我做console.log(this.model.get('contacts'));我越來越空的對象......可能是一些異步的東西我想念:( – user2167526