2013-07-02 114 views
1

我在骨幹網與外部JSON像這樣的應用程序:骨幹GROUPBY收集下劃線

[ 
    { 
    "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" 
    } 
] 

我想HOTEL_ID GROUPBY後,解析並獲取它,並建立逐級gropued數組..
我也試試這個,但我有空數組:

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

對於初學者應引用以'this'爲前綴的View/Model/Router內的所有變量。爲了清楚起見,我在'initialize'上面聲明它們(儘管如果它們不存在,它們將會被創建) –

回答

3

它看起來像你這樣做它是正確的。

  1. 檢查您的網絡選項卡 - 是正在進行的調用,是json被成功返回?
  2. 你爲了你的收藏之前,具有收藏被填充(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調用並創建自己的調用會很有用,但您應該傾聽取回的successerrorhttp://backbonejs.org/#Collection-fetch