2013-07-07 102 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