2014-01-20 26 views
0

我正在學習Backbone,如果有人能幫助我解決這個問題,那將會很棒。在我對集合進行讀取操作後,在成功回調函數中,我使用collection.toJSON()獲得瞭解析數據,這實際上返回了一個對象,我無法從此對象中獲取任何內容。這個對象實際上有我需要的數據。Backbone.js無法解析來自collectio.toJSON的響應()

Please see the object contents in this screenshot

我的問題是我怎麼訪問行財產在我的對象。這是我給大家參考

var testCollection = Backbone.Collection.extend({ 
    model:myModel, 
    url: '/myApiEndPoint', 
    data: '', 
    initialize: function(models, options) { 
     this.data = models.data; 
    }, 
    fetch: function(options) { 
     var ajaxConfig = { 
      url: this.url, 
      data: this.data, 
      type: 'POST', 
      dataType: 'text', 
      contentType: 'text/xml', 
      parse: true 
     }; 
     options = _.extend({}, ajaxConfig, options); 

     return Backbone.Collection.prototype.fetch.call(this, options); 
    }, 
    parse: function(xmlResponse) { 
      // I have some parsing logic to extract uid and rows from my xmlResponse 
      return { 
       uid: uid, 
       rows: rows 
      }; 
     }, 
    }); 

var collObj = new testCollection({data: xmlQuery1}); 
collObj.fetch({ 
    success: function(collection){ 
    // This code block will be triggered only after receiving the data. 
    console.log(collection.toJSON()); 
    } 
}); 

回答

1

正如其名稱所暗示toJSON,它會返回JSON對象的數組,其中每個對象爲Model's JSON對象代碼。您可以通過這種方式獲取所需的屬性:

collObj.fetch({ 
    success: function(collection){ 
    // This code block will be triggered only after receiving the data. 
    console.log(collection.toJSON()); 
    var uid = 'uid-of-an-object-to-access'; 
    var rows = collection.get(uid).get('rows'); 
    console.log(rows); 
    } 
});