Skip to content

Instantly share code, notes, and snippets.

@spullen
Created August 22, 2013 23:36
Show Gist options
  • Save spullen/6314034 to your computer and use it in GitHub Desktop.
Save spullen/6314034 to your computer and use it in GitHub Desktop.
Send a JSON collection with custom headers to describe the entire paginated collection. This removes mixing meta data about the paginated collection with the actual data we want to work with.
// using Backbone.Pageable https://github.com/wyuenho/backbone-pageable
App.Collections.Protocols = Backbone.PageableCollection.extend({
model: App.Models.Protocol,
url: '/protocols',
state: {
firstPage: 1,
currentPage: 1,
pageSize: 100
},
queryParams: {
},
parse: function(response, options) {
this.currentPage = parseInt(options.xhr.getResponseHeader('X-Current-Page'));
this.totalPages = parseInt(options.xhr.getResponseHeader('X-Total-Pages'));
return response;
}
});
class ProtocolsController < ApplicationController
respond_to :json
# ...
def index
@protocols = Protocol.ordered.paginate(page: params[:page], per_page: 100)
response.headers['X-Current-Page'] = @protocols.current_page.to_s
response.headers['X-Total-Pages'] = @protocols.total_pages.to_s
respond_with @protocols
end
# ...
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment