我正在主干中构建我的第一个应用程序,我想知道哪种模式是解析多级 json 的最佳模式。这是一个简单的json小例子:
{
"hotels":[
{
"hotel" : [
{
"name" : "Hotel1"
}
]
},
{
"hotel" : [
{
"name" : "Hotel2"
}
]
},
{
"hotel" : [
{
"name" : "Hotel3"
}
]
}
]
}
要打印它,我在主干中使用集合和视图,如下所示: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>
但是我无法打印值名称,该怎么做?谢谢