Paginated JSON Backbone Collection

时间:2014-12-28 21:58:35

标签: javascript json backbone.js pagination

我试图想要创建一个从第三方api中提取的图像网址集合,这些网址目前将每个页面只有5个图像的JSON打包为分页。我不确定如何构建我的解析方法,以便我可以在一开始就收集20个网址。

我对如何调用我的网址感到困惑,以便我可以按照下一页的说明进行操作。链接。我想到的一种方法是创建两个集合 - 一个基本集合,它实例化另一个具有不同结尾的集合,用于' url'直到达到所需的网址数量。

我的JSON看起来像:

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

1 个答案:

答案 0 :(得分: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接收的对象,您可能希望对响应进行一些解析。如果您需要有关如何有效管理此集合的模型的一些指示,请告诉我。