2012-11-13 66 views
3

我目前必須在下面編寫代碼和一個靜態json文件。但是,我怎樣才能將我的模型默認設置爲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" 
}] 
} 

回答

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文件的方法。

1

我想解決一個類似的問題(從演示的靜態JSON文件填充Backbone模型)。

我碰到一個例子就是在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)是一個容納了JSON筆者文本區域(LuizArmesto)正試圖加載到模型中。

<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> 

正如他的評論指出,這是不是地道的骨幹(或「主幹路」),但它不需要服務器副作用小項目的偉大工程。