Last active
August 29, 2015 13:58
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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