3

我目前必须在下面编写代码和一个静态 json 文件。但是如何将我的模型默认设置为 json 文件中的数据?我的 JSON 文件有几页 - 我希望能够获取默认值并设置默认值。

var PageModel = Backbone.Model.extend({
initialize: function () {
    console.log('initiliazed model');
},

url: "data/data.json",

defaults: function() {
    return PageView.defaultsFromJSON;
}

});

var PageView = Backbone.View.extend ({
initialize: function () {
    console.log('initiliazed view')
    _.bindAll(this);
    this.model.fetch();
    this.render();
    this.model.on('change',this.render);
},

el : '#ev-wrapper',

render: function () {
    $('#ev-wrapper').append(Handlebars.compile($('#ev-template').html())(this.model.toJSON()));

    $('.ev-asset-loader').fadeOut('slow', function (event) {
        this.remove();

    });
}

});

pageModel = new PageView({model: new PageModel()});

json 文件 -

{
"page":[{
        "id":"p05",
        "title":"ptitle1",
        "text":"pinitialtext"
},
{
        "id":"p10",
        "title":"ptitle2",
        "text":"pinitialtext"
}]
}
4

2 回答 2

1

您是否使用服务器端语言呈现页面?如果是,则将 JSON 字符串注入包含默认值的视图中,并用它填充模型。

var data = <?php echo $json ?>, 
    model = new PageModel(data),
    view = new PageView({model: model, el : $('#ev-wrapper')[0]});

如果您不使用服务器端语言,我认为您可以使用 JQuery 发出 AJAX 请求来加载您的 JSON 数据,但这与调用fetch.

我看不到以另一种方式“包含”JSON文件的方法。

于 2012-11-13T19:14:48.257 回答
1

我正在尝试解决类似的问题(Populating Backbone models from a static JSON file for a demo)。

我在 Backbone.Leaflet 库中遇到了一个示例: https ://github.com/LuizArmesto/backbone.leaflet/blob/master/examples/map.html

 // This isn't the backbone way, but we want to keep this example
  // as simple as possible.
  $( '#render' ).click( function () {
    geoCollection.reset( JSON.parse( $( '#geoJSON' ).val() ) );
  });

在此示例中,相关 ID (#geoJSON) 是一个文本区域,其中包含作者 (LuizArmesto) 尝试加载到模型中的 JSON。

 <textarea id="geoJSON">
{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "geometry": {
        "type": "Polygon",
        "coordinates": [[[-46.6155, -23.5023], [-46.6193, -23.5030], [-46.6247, -23.5073], [-46.6252, -23.5117], [-46.6218, -23.5115], [-46.6154, -23.5080], [-46.6150, -23.5037], [-46.6155, -23.5023]]]
      },
      "properties": {}
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "LineString",
        "coordinates": [[-46.6318, -23.4900], [-46.6256, -23.4916], [-46.6200, -23.4900], [-46.6100, -23.4900]]
      },
      "properties": {}
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [-46.6368, -23.5100]
      },
      "properties": {}
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [-46.6156, -23.5016]
      },
      "properties": {}
    }
  ]
}

</textarea>

正如他在评论中所说,这不是骨干网(或“骨干网方式”)的惯用语,但它对于不需要服务器的小型副项目非常有用。

于 2014-04-17T14:25:38.790 回答