0

In my Application, I have the following JSON data format:

{
    Item: {
        property1: '',
        ...
    }
}

Following the solution of this stackoverflow.com answer, I modeled my Backbond.js models the following way:

App.Models.Item = Backbone.Model.extend({

});

App.Models.ItemData = Backbone.Model.extend({
    defaults: {
        'Item': new App.Models.Item
    }
});

I now want to bootstap the data to my App from the Backend system on the page load the following way:

var item = App.Models.ItemData({
    {Item: 
        {property1: 'data'}
    }
});

The problem I have now is that item.get('Item') returns a plain JavaScrip object and not a Backbone.Model object, because the defaults are overwritten. How can I create the Backbone.js object while ensuring that item.get('Item') is an App.Models.Item object?

I also have read that if you nest Backbone.Models, you should wirite custom getter methods, so the rest of your app dose not have to know about the internal data structure. If so, what is the right way to implement those setters and getters?

Community
  • 1
  • 1
wowpatrick
  • 5,082
  • 15
  • 55
  • 86

1 Answers1

2

You can override the parse method on your ItemData model. No defaults required. The parse method will initialize an empty model, if one is not passed:

App.Models.ItemData = Backbone.Model.extend({
   parse: function(attrs) {
     attrs = attrs || {};
     if(!(attrs.Item instanceof App.Models.Item))
       attrs.Item = new App.Models.Item(attrs.Item);

     return attrs;
   }
});

And then initialize your ItemData model with the option parse:true:

var item = new App.Models.ItemData({Item:{property1: 'data'}}, {parse:true});
jevakallio
  • 35,324
  • 3
  • 105
  • 112
  • Thanks for the quick response! Just two small questions: 1. Why the do we need the `attrs = attrs || {};`? 2. I had to change `if(!attrs.Item instanceof App.Models.Item)` to `if(!(attrs.Item instanceof App.Models.Item))` to work. What's going on there? – wowpatrick Feb 01 '13 at 14:22
  • @wowpatrick, defaulting `attrs` to `{}` is just a guard in case someone passes a null/undefined value to the method, in which case the property access `attrs.Item` would cause an error. You could also do `if(attrs) { ... }` but this is how I usually do it. – jevakallio Feb 01 '13 at 14:30
  • Also added missing parentheses to the `instanceof` check, sorry about those. Without parens the `!attrs.Item` was evaluated first, and returned to a boolean value, which was never `instanceof` anything. – jevakallio Feb 01 '13 at 14:31
  • I think you also need a 'new' when instantiating the ItemData model. – robmisio Feb 01 '13 at 14:47
  • ouch @robmisio, of course. I just copies the instantiation from OP's post, didn't check. Laziness bites. – jevakallio Feb 01 '13 at 14:52