I'm buiding my first app in backbone and I want to know which is the best mode to parse a json with multiple level. This is a simple small example of json:
{
"hotels":[
{
"hotel" : [
{
"name" : "Hotel1"
}
]
},
{
"hotel" : [
{
"name" : "Hotel2"
}
]
},
{
"hotel" : [
{
"name" : "Hotel3"
}
]
}
]
}
To print it I'm using collection and view in backbone like this:
COLLECTION:
var HotelsCollection = Backbone.Collection.extend({
model: Hotel,
url: "includes/test-data.json",
parse : function(response){
return response.hotels;
}
});
And this is the two view called view because every hotel I'd like to have a different view:
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}));
}
});
My template is:
<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>
But doesn't print name I have also tried:
<script type="text/template" id="hotel-list-template">
<div>
<h1>TEMPLATE HOTEL funziona
<a class="btn"><%= hotel.name %></a>
</h1>
</div>
</script>
But I can't print the value name, how to do that?
Thanks
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…