Backbone.js无法解析collectio.toJSON()的响应

时间:2014-01-20 01:24:35

标签: javascript backbone.js

我正在学习Backbone,如果有人可以帮我解决这个问题,那将会很棒。在我对我的集合进行获取后,成功回调我使用collection.toJSON()获取解析数据,这实际上返回一个对象,我无法从该对象中获取任何内容。这个对象实际上有我需要的数据。

Please see the object contents in this screenshot

我的问题是如何访问对象中的rows属性。这是我的代码供您参考

  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 个答案:

答案 0 :(得分: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);
  }
});