簡體   English   中英

分頁JSON骨干集合

[英]Paginated JSON Backbone Collection

我試圖找出從第三方api提取圖像URL的集合,該api當前將其JSON分頁為每頁5張圖像。 我不確定如何構造解析方法,以便一開始就可以收集二十個網址。

我對如何稱呼我的URL感到困惑,因此我只能點擊“下一頁”鏈接。 我正在考慮的一種方法是創建兩個集合-一個基礎集合,該實例化實例化具有“ url”結尾的另一個集合,直到獲得所需數量的url。

我的JSON看起來像:

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

在您的情況下,一次獲取取決於最后一次獲取(對於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接收到的對象,您可能希望對響應進行一些解析。 讓我知道您是否需要一些有關如何有效管理此集合的模型的指導。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM