backbone.js – 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的解析函数,以便按照你想要的方式构造数据.从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)
    };
  }
});

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

点赞