我在骨干网中有一个从服务器检索数据的应用程序。这个数据是hotels and foreach hotel 我有更多房间。我将酒店分为一个 json 和另一个 json 中的房间,如下所示:
酒店.json
[
{
"id": "1",
"name": "Hotel1"
},
{
"id": "2",
"name": "Hotel2"
},
{
"id": "3",
"name": "Hotel3"
}
]
房间.json
[
{
"id" : "r1",
"hotel_id" : "1",
"name" : "Singola",
"level" : "1"
},
{
"id" : "r1_1",
"hotel_id" : "1",
"name" : "Doppia",
"level" : "2"
},
{
"id" : "r1_3",
"hotel_id" : "1",
"name" : "Doppia Uso singol",
"level" : "1"
},
{
"id" : "r2",
"hotel_id" : "2",
"name" : "Singola",
"level" : "1"
},
{
"id" : "r2_1",
"hotel_id" : "2",
"name" : "Tripla",
"level" : "1"
}
]
我想把每家酒店和它的房间结合起来(外部钥匙进入rooms.json
hotel_id
)并打印房间的组合:foreach level 结合不同的房间。
一楼一间,二楼一间,三楼一间。
最高级别是 3,但我只能有一个级别或只有两个级别。如果我有 3 级,我不想在没有 3 级的情况下将 1 级和 2 级结合起来。
像这样的东西
Room "Single", "level" : "1" , "hotel_id" : "1"
Room "Double", "level" : "2" , , "hotel_id" : "1"
Room "Triple", "level" : "3" , , "hotel_id" : "1"
Room "Double for single", "level" : "1" , "hotel_id" : "1"
Room "Double", "level" : "2" , , "hotel_id" : "1"
Room "Triple", "level" : "3" , , "hotel_id" : "1"
我认为这个房间的构造函数是将 renderRooms 放入我的应用程序中。
这是我的应用程序:
var Room = Backbone.Model.extend();
var Rooms = Backbone.Collection.extend({
model: Room,
url: "includes/rooms.json"
});
var Hotel = Backbone.Model.extend({
defaults: function() {
return {
"id": "1",
"name": "Hotel1",
"rooms": []
}
}
});
var HotelCollection = Backbone.Collection.extend({
model: Hotel,
url: "includes/test-data.json",
initialize: function() {
console.log("Collection Hotel initialize");
}
});
var HotelView = Backbone.View.extend({
template: _.template($("#hotel-list-template").html()),
initialize: function() {
this.collection = new HotelCollection();
this.collection.bind('sync', this.render, this);
this.collection.fetch();
},
render: function() {
console.log('Data hotel is fetched');
this.bindRoomToHotel();
var element = this.$el;
element.html('');
},
bindRoomToHotel: function() {
allRooms = new Rooms();
allRooms.on("sync", this.renderRooms, this)
allRooms.fetch();
},
renderRooms: function() {
$(this.el).html(this.template({ hotels: this.collection.models }));
}
});
var hotelView = new HotelView({
el: $("#hotel")
});
如何创建这个房间组合并打印出来?
有什么好的方法还是有更好的方法?