我正在将我的第一个应用程序构建在骨干网中,我想知道哪种方法是解析具有多个级别的json的最佳模式。这是一个简单的json小示例:
{ "hotels":[ { "hotel" : [ { "name" : "Hotel1" } ] }, { "hotel" : [ { "name" : "Hotel2" } ] }, { "hotel" : [ { "name" : "Hotel3" } ] } ] }
要打印它,我正在使用collection并在主干中查看,如下所示:COLLECTION:
var HotelsCollection = Backbone.Collection.extend({ model: Hotel, url: "includes/test-data.json", parse : function(response){ return response.hotels; } });
这就是称为视图的两个视图,因为我想要的每个酒店都有不同的视图:
var AppView = Backbone.View.extend({ initialize: function(){ this.collection = new HotelsCollection(); this.collection.bind('sync', this.render, this); this.collection.fetch(); }, render: function(){ console.log('Data is fetched'); var element = this.$el; element.html(''); this.collection.each(function(model){ console.log('new hotel'); var hotelView = new HotelView({model:model}); element.append(hotelView.el); }); } }); var HotelView = Backbone.View.extend({ template: _.template($("#hotel-list-template").html()), initialize: function(){ console.log('HotelView initialized'); this.render(); }, render: function(){ console.log('HotelView render'); $(this.el).html(this.template({model: this.options.model})); } });
我的模板是:
<script type="text/template" id="hotel-list-template"> <div> <h1>TEMPLATE HOTEL funziona? <% _.each(hotel, function(acs) { %> <a class="btn"><%= name %></a> <% }); %> </h1> </div> </script>
但是不打印名称,我也尝试过:
<script type="text/template" id="hotel-list-template"> <div> <h1>TEMPLATE HOTEL funziona <a class="btn"><%= hotel.name %></a> </h1> </div> </script>
但是我无法打印值名称,该怎么做?谢谢
首先,JSON结构确实非常奇怪。修理服务器或请服务器团队寻求治疗。但是,假设您无法取消嘲笑服务器的JSON,以下是将其变成与主干兼容的数组的方法:
var HotelsCollection = Backbone.Collection.extend({ model: Hotel, url: "includes/test-data.json", parse: function(response){ //remove prefix/wrapper object and collect "hotel" 1-element arrays var sillyArrays = _.pluck(response.hotels, 'hotel'); //Extract the hotel objects from their silly 1-element arrays //Synthesize a fake id attribute since backbone expects that var hotels = _.map(sillyArrays, function (hotelArray, index) { return {name: hotelArray[0].name, id: index + 1}; }); return hotels; } });
该parse函数将返回该数据,主干将理解。
parse
[ { name: 'Hotel1', id: 1 }, { name: 'Hotel2', id: 2 }, { name: 'Hotel3', id: 3 } ]
还要注意,缺少id属性是您最终需要解决的另一件事,以便您的应用程序能够与骨干网一起正常工作。
id