Skip to content

Instantly share code, notes, and snippets.

@burtyish
Last active August 29, 2015 13:58
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save burtyish/10006579 to your computer and use it in GitHub Desktop.
Save burtyish/10006579 to your computer and use it in GitHub Desktop.
An extension of Backbone.PageableCollection to parse server responses created by Django Rest Framework.
define [
'jquery',
'underscore',
'backbone',
'backbone-pageable'
], ($, _, Backbone) ->
###
An extension of Backbone.PageableCollection to parse server responses created by Django Rest Framework.
The response structure is expected to match that provided by django-rest-framework's Pagination mechanism
(http://www.django-rest-framework.org/api-guide/pagination)
Example response:
{
'count': 4,
'next': '?page=2',
'previous': null,
'results': ['john', 'paul']
}
###
class Backbone.DjangoPageableCollection extends Backbone.PageableCollection
# Name of the attribute containing the array of records
resultsField: 'results'
totalRecordsField: 'count'
nextField: 'next'
previousField: 'previous'
parseRecords: (resp, options) ->
if resp and _.has(resp, @resultsField) and _.isArray(resp[@resultsField])
resp[@resultsField]
else
Backbone.PageableCollection.prototype.parseRecords.apply(this, arguments)
parseState: (resp, queryParams, state, options) ->
state =
totalRecords: resp[@totalRecordsField]
parseLinks: (resp, options) ->
links =
prev: resp[@previousField]
next: resp[@nextField]
first: null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment