2013-08-01 40 views
3

我是Backbone的新手,我對將(對象)JSON數組傳遞給Backbone集合時發生了什麼感到困惑。將JSON數組傳遞給Backbone Collection時錯誤的collection.length

我從託管在Google雲端硬盤上的電子表格中提取一些JSON。我正在解析這些數據,因爲我想在我的集合中使用的實際數據是深深嵌套的。在我的解析函數中,如果我記錄了我想要的數組的長度,我得到了157(這是正確的)。然後我將該數組傳遞給Backbone集合,並且我的集合的長度爲1(不正確)。就好像foo.bar.length = 157,但'foo'中只有一個'bar',所以當我將foo.bar傳入集合時,它需要foo.bar而不是foo.bar的內容!很困惑。下面

代碼...

var table = new TableView(); 

TableItem = Backbone.Model.extend(), 

TableItemCollection = Backbone.Collection.extend({ 
    model : TableItem, 
    url : 'https://spreadsheets.google.com/feeds/list/0AjbU8ta9j916dFdjSVg3YkNPUUJnWkZSWjBDWmZab3c/1/public/basic?alt=json-in-script', 
    sync : function(method, model, options) { 
     var params = _.extend({ 
      type: 'GET', 
      dataType: 'jsonp', 
      url: this.url, 
      processData: false 
     }, options); 
     return $.ajax(params); 
    }, 
    parse : function(resp, xhr) { 
     console.log(resp.feed.entry.length); // THIS LOGS 157 
     return resp.feed.entry; 
    } 
}), 

TableView = Backbone.View.extend({ 
    initialize : function (options) { 
     this.collection = new TableItemCollection(); 
     this.collection.on('reset', this.parseResponse, this); 
     this.collection.fetch({ 
      reset : true, 
      success : function (model, response, options) { 
       console.log('OK'); // THIS LOGS 'OK' 
      }, 
      error : function (model, response, options) { 
       console.log('ERROR'); 
      } 
     }); 
    }, 
    parseResponse : function() { 
     console.log(this.collection.length); // THIS LOGS 1 
    } 
}); 
+0

「resp.feed.entry」的類型是什麼?你確定它是一個數組嗎?請註銷你的解析方法'console.log(_。isArray(resp.feed.entry))'! – nemesv

回答

3

如果你傾倒通過谷歌電子表格返回的項目之一,您將看到數據被嵌套在多個對象,像這樣

{ 
    "id":{"$t":"https://spreadsheets.google.com/feeds/list/..."}, 
    "updated":{"$t":"2013-07-30T12:01:24.000Z"}, 
    "category":[{"scheme":"...","term":"..."}], 
    "title":{"type":"text","$t":"ACIW"}, 
    "content":{}, 
    "link":[{"rel":"self","type":"application/atom+xml","href":"..."}] 
} 

In a Fiddle http://jsfiddle.net/nikoshr/kHBvY/

請注意id屬性是如何包裝在對象中的"id":{"$t":"https://spreadsheets.google.com/feeds/list/0AjbU8ta9j916dFdjSVg3YkNPUUJnWkZSWjBDWmZab3c/1/public/basic/cokwr"}

主幹集合不允許重複,並且根據它們的ID確定重複項。您的所有商品都被視爲重複商品併合併爲一個。如果你刪除了ID或者消除了這個ID,你會得到你的157個物品。例如,

parse : function(resp, xhr) { 
    var data = resp.feed.entry, i; 
    console.log(data.length); // THIS LOGS 157 

    for (i=data.length-1; i>=0; i--) 
     data[i].id = data[i].id['$t']; 

    return data; 
} 

http://jsfiddle.net/nikoshr/kHBvY/2/用於演示

你可能要解開所有屬性的非揪頭髮的方式來使用它們。

+0

當然!非常感謝,總是有道理。 *捂臉* – user2641989