我在Backbone中有一个带有外部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"
}
]
我想解析并获取它,并在groupBy之后通过hotel_id创建一个按级别开发的数组..
我试过这个,但我有空数组:
var Room = Backbone.Model.extend();
var Rooms = Backbone.Collection.extend({
model:Room,
url : "includes/rooms.json"
});
var RoomView = Backbone.View.extend({
initialize: function(){
allRooms = new Rooms();
allRooms.on("sync", this.render, this)
allRooms.fetch();
},
render: function(){
var rooms = _.groupBy(allRooms.models,'hotel_id');
for (var hotelid in rooms)
rooms[hotelid] = _.groupBy(rooms[hotelid], "level");
}
});
如果我追踪它,请给我一个空的房间阵列
答案 0 :(得分:3)
看起来你做得对。
console.log it
)
// Define the model
var Room = Backbone.Model.extend();
// Define the collection
var Rooms = Backbone.Collection.extend(
{
model: Room,
url: 'includes/rooms.json',
});
// Define the View
var RoomsView = Backbone.View.extend({
roomCollection: null,
initialize: function() {
this.roomCollection = new Rooms;
var that = this;
this.roomCollection.fetch({
success: function () {
that.render();
}
});
},
render: function() {
console.log(this.roomCollection.toJSON());
// Note: Haven't tested your logic
var rooms = _.groupBy(this.roomCollection.models,'hotel_id');
for (var hotelid in rooms)
rooms[hotelid] = _.groupBy(rooms[hotelid], 'level');
console.log(rooms);
}
});
我注意到的一件事是你正在听sync
- sync
是执行ajax调用的方法。如果您想覆盖ajax调用并创建自己的调用,这很有用,但您应该听取fetch的success
和error
。 http://backbonejs.org/#Collection-fetch