【问题标题】:Paginated JSON Backbone Collection分页 JSON 主干集合
【发布时间】:2014-12-29 09:59:40
【问题描述】:

我正在尝试创建一个从第三方 api 提取的图像 url 集合,该 api 当前将其 JSON 呈现为分页,每页只有 5 个图像。我不知道如何构造我的解析方法,以便一开始就可以收集 20 个 url。

我对如何调用我的 url 感到困惑,以便我可以点击“下一页”链接。我正在考虑的一种方法是创建两个集合 - 一个基础集合实例化另一个具有不同结尾的“url”集合,直到达到所需数量的 url。

我的 JSON 看起来像:

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

【问题讨论】:

  • 您确定 API 将您限制为每页 5 张图片吗?我怀疑 5 是默认值,您会发现在 API 中使用不同的设置增加它的可能性。
  • 谢谢——我刚刚添加了一个查询字符串,现在它可以工作了——谢谢!

标签: javascript json backbone.js pagination


【解决方案1】:

鉴于您的场景,其中一次提取依赖于最后一次提取(对于 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 接收的对象,您可能希望对响应进行一些解析。如果您需要有关如何有效管理此集合的模型的一些指示,请告诉我。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-30
    • 1970-01-01
    • 2012-10-15
    相关资源
    最近更新 更多