Skip to content

Instantly share code, notes, and snippets.

@Tronix117
Last active August 29, 2015 14:01
Show Gist options
  • Save Tronix117/f8d3f23819e2fa737d8a to your computer and use it in GitHub Desktop.
Save Tronix117/f8d3f23819e2fa737d8a to your computer and use it in GitHub Desktop.
Backbone pagination using Content-Range header
# Backbone Pagination with header
#
# Get remote number of resources, and add it in the `remoteCount` attribute of the collection
# this attribute can then be use to create proper pagination.
#
# Expected format is an header `Content-Range` with following format:
# `resource 40-49/234` (HTTP 1.1 format)
# * `resource` is the name of the resource (can be `resource`, not important)
# * `40-49` is the range of returned items (item 40 to item 49)
# * `234` is the total number of items (this is the important part)
#
# @author Jeremy Trufier <[email protected]> (https://github.com/Tronix117)
# @gist https://gist.github.com/Tronix117/8816559
# @license MIT
# -------------------------------------
Backbone.syncWithPagination = (method, model)->
arguments[2] = (resp, status, xhr)->
range = xhr.getResponseHeader('Content-Range')
model.remoteCount = count if range and (count = range.split('/')[1])
success.apply @, arguments
Backbone.syncWithoutPagination.apply @, arguments
Backbone.syncWithoutPagination = Backbone.sync
Backbone.sync = Backbone.syncWithPagination
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment