2014-12-28 76 views
0

我試圖找出創建一個圖像網址集合從第三方api拉,目前呈現他們的JSON分頁,每頁只有5個圖像。我不確定如何構建我的分析方法,以便我可以在一開始就收集二十個網址。分頁的JSON骨幹收集

我很困惑什麼叫我的網址,所以我可以按照'下一頁'鏈接。我想到的一種方法是創建兩個集合 - 一個基本集合,該集合實例化具有「url」的不同結尾的另一個集合,直到達到所需的url數量。

我的JSON的樣子:

{ data: [url1, url2, url3, url4, url5], 
    pagination: {current_page: 2, next_page: "link1", previous_page: "link3", per_page: 5} 
} 
+2

您確定API限制您每頁5張圖片嗎?我懷疑5是一個默認值,並且你會發現在API中增加一個不同設置的可能性。 – mwarren

+0

謝謝,我剛剛添加了一個查詢字符串,現在它的工作原理 - 謝謝! – sfahlberg

回答

0

鑑於您的情況,其中一個取依賴於最後的取(對於next_link),我覺得有點遞歸可能會有所幫助。你可以做連續的提取,觸發服務器響應。我會在我的視圖中創建以下功能:

Backbone.View.extend({ 
    initialize: function() { 
    this.numOfFetches = 5 // Depends on how many urls you want to end up with 

    // Start the recursion 
    this.fetchUrls(this); // Pass int the context so it'll be available throughout 
          // the recursion 
    } 

    fetchUrls: function (context) { 
    this.collection.fetch({remove: false}) 
    // Backbone.sync returns jQuery Promises 
    // so we can take advantage of the Promise methods 
    .done(function(response) { 
     if (--context.numOfFetches > 0) { 
     // Set up the url for the next fetch 
     context.collection.url = response.pagination.next_page 
     // Iterate the recursion 
     context.fetchUrls(context); 
     } 
    }) 
    // Do something different if the call fails 
    .fail(function() { 
     // If you want to fetch the next page even on fail 
     // you can use the .always() Promise method instead of 
     // .done() and remove this .fail() method 
    }) 
    } 
}); 

幾點。首先,注意我們如何通過{ remove: false }選項collection.fetch。這是至關重要的。它告訴collection.set在服務器返回數據時添加(或合併現有的)模型。沒有它,它會刪除所有不符合上次響應的模型。其次,爲了方便起見,我將numOfFetches屬性附加到您的視圖中(爲方便起見,在intialize中),因爲遞歸會需要父範圍中的變量,每個遞歸都不會重新初始化該變量。第三,考慮到你將要從API接收到的對象,你可能會想對響應進行一些解析。讓我知道你是否需要一些關於如何有效管理這個集合模型的指針。