icereval / backbone-documentmodel

A plugin to create entire Document structures with nested Backbone.js Models & Collections with deep model references and event bubbling.
MIT License
66 stars 8 forks source link

getNestedModel() and getNestedCollection() methods invoked only for first level attributes #17

Open skotchio opened 10 years ago

skotchio commented 10 years ago

In the following JSON object:

var user = {
  addresses: [
      { type: 'Shipping', city: 'Charlottesville', state: 'VA',
             items: [
                   {id: 1, name: "item1"},
                   {id: 2, name: "item2"}
             ] 
      },
      { type: 'Billing', city: 'Prescott', state: 'AZ',
             items: [
                   {id: 1, name: "item1"},
                   {id: 2, name: "item2"}
             ] 
       }
  ]
};

I can't to override nested collection for 'items' and model for 'items' children:

User = Backbone.DocumentModel.extend({

    getNestedModel: function (nestedKey, nestedValue, nestedOptions) {
          console.log("Never executed here");

         return new Backbone.DocumentModel(nestedValue, nestedOptions);
    },    

    getNestedCollection: function (nestedKey, nestedValue, nestedOptions) {
           console.log('nestedKey is "addresses" only' );

           return new Backbone.DocumentCollection(nestedValue, nestedOptions);
    }
});

var john = new User(user);  
lukasbuenger commented 10 years ago

It is true that getNestedModel() and getNestedCollection() methods only get invoked for first level attributes and this is, at the moment at least, quite intended. It may take you a few more nested custom classes (for ItemCollection at first level and ItemCollection.model = Item at second level), but the instantiation of nested values within nested models and collections should IMHO always get delegated to the designated nested model class to keep things consistent and decoupled. If someone has a suggestion how to implement this without breaking the aforementioned conditions, I'd love to help.

casparss commented 10 years ago

Yeah I have just recently run into this issue and it's a massive drawback! I can't have run fetches and sync operations with out explicitly supplying URLs, it's really not ideal. Anyone thinking of working on this?