Search code examples
backbone.jsbackbone-viewsbackbone.js-collectionsbackbone-model

Nested Models and Collection in backbonejs


I am looking for a solution to load the nested json in the parent model to be eventually rendered on screen. I have a nested json in this format:

{
     "name":"Hotel-A",
     "description":"5 star rating",
     "geographicAddress":{
        "streetAddress":"343,Market st",
        "city":"San Jose",
        "state":"CA",
        "country":"USA",
        "postalCode":"34523"
     },
     "id":"338a947b-c488-46a9-b68f-640fcda38577"
  }

I have a parent model which further has reference to geographicAddress and geographicPoint model.

This is how it looks:

Parent model:

defaults:{
    "id" : "",
    "name" : "",
    "description" : "",
    "geographicAddress": new geoAddress(),
}

Parent Collection:

    addParentModel: function(parent) {
        var newParentModel = new this.model();
         newParentModel.set({
                id: parent.id,
                name: parent.name,
                description: parent.description,
                address:geoAddress.streetAddress,
                city:geoAddress.city,
                state:geoAddress.state,
                postalCode:geoAddress.postalCode

            });

geographic Address Model:

defaults:{
            "streetAddress":"",
            "city":"",
            "state":"",
            "country":"",
            "postalCode":""
        }

Could someone show me a way to populate the parent model with the nested json and render it in html.

Thank you.


Solution

  • I would suggest overriding Backbone.Model's parse function in order to structure the data how you want. From the Backbone documentation:

    The function is passed the raw response object, and should return the attributes hash to be set on the model. The default implementation is a no-op, simply passing through the JSON response. Override this if you need to work with a preexisting API, or better namespace your responses.

    var PlaceModel = Backbone.Model.extend({
      defaults: {
        "id": "",
        "name": "",
        "description": "",
        "geographicAddress": new AddressModel()
      },
      parse: function(data) {
        return {
          id: data.id,
          name: data.name,
          description: data.description,
          geographicAddress: new AddressModel(data.geographicAddress)
        };
      }
    });
    

    I've created a more complete demo that shows creating models using parse and then rendering a collection here: https://jsfiddle.net/f8L2z0ba/