0

I am trying to nest a Collection View into a Model View.

In order to do so, I used Backbone's Marionnette Composite View and followed that tutorial

At the end he initializes the nested collection view like this:

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

});

How would you go doing the same without using the addInitalizer from Marionette?

In my project I am fectching data from the server. And when I try doing something like:

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


 });

I get an "indefined options" coming from the collection:

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

1 回答 1

0

那是因为当您创建 时contactCollection,您没有在对象中提供candidatures集合。options您确实需要将您的联系人集合初始化代码修改为:

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

这样,candidature属性将设置为提供的值(如果未提供,则为undefined)。

然后,您仍然需要在实例化集合时提供信息:

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

PS:我希望你发现我的博客文章有用!

于 2013-07-07T17:41:21.753 回答