backbonejs 中的嵌套模型和集合

Nested Models and Collection in backbonejs

我正在寻找一种解决方案来加载父模型中的嵌套 json,最终在屏幕上呈现。 我有一个嵌套的 json 这种格式:

{
     "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"
  }

我有一个父模型,它进一步引用了 geographicAddress 和 geographicPoint 模型。

这是它的样子:

父模型:

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

父集合:

    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

            });

地理地址模型:

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

谁能告诉我用嵌套 json 填充父模型并在 html 中渲染它的方法。

谢谢。

我建议重写 Backbone.Model 的 parse 函数,以便按照您的需要构建数据。来自 Backbone 文档:

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

我创建了一个更完整的演示,展示了使用 parse 创建模型,然后在此处渲染集合:https://jsfiddle.net/f8L2z0ba/