Skip to content

Instantly share code, notes, and snippets.

@tcjr
Last active December 25, 2015 06:59
Show Gist options
  • Save tcjr/6935684 to your computer and use it in GitHub Desktop.
Save tcjr/6935684 to your computer and use it in GitHub Desktop.
Basic pagination with Ember
// The API accepts the page parameter and returns the pagination info in meta
{
"messages": [ ... ],
"meta": {
"pagination": {
"total_pages": 3,
"current_page": 1,
"total_count": 55
}
}
}
/*
This can be mixed into a route to provide pagination support.
*/
App._PaginatedRouteMixin = Ember.Mixin.create({
paginationRoute: Ember.required(String),
// This function is for use in a route that calls find() to get a
// paginated collection of records. It takes the pagination metadata
// from the store and puts it into the record array.
_includePagination: function(records){
var metadata = records.store.typeMapFor(records.type).metadata;
// put the pagination content directly on the collection
records.set('pagination', metadata.pagination);
return records;
},
actions: {
gotoPage: function(pageNum){
var last = this.get('controller.content.pagination.total_pages') || 1;
var num = Util.clamp(pageNum, 1, last);
this.transitionTo(this.paginationRoute, num);
},
nextPage: function(){
var cur = this.get('controller.content.pagination.current_page') || 0;
this.transitionTo(this.paginationRoute, cur + 1);
},
previousPage: function(){
var cur = this.get('controller.content.pagination.current_page') || 2;
this.transitionTo(this.paginationRoute, cur - 1);
},
lastPage: function(){
var last = this.get('controller.content.pagination.total_pages') || 1;
this.transitionTo(this.paginationRoute, last);
},
firstPage: function(){
this.transitionTo(this.paginationRoute, 1);
}
}
});
// MODEL
App.Message = DS.Model.extend({
created_at: DS.attr('date'),
text: DS.attr('string')
});
// ROUTES
App.MessagesIndexRoute = Ember.Route.extend({
redirect: function(){
this.transitionTo('messages.page', 1);
}
});
App.MessagesPageRoute = Ember.Route.extend(App._PaginatedRouteMixin, {
paginationRoute: 'messages.page',
model: function(params){
var query = { page: params.num };
return this.get('store').find('message', query).then(this._includePagination);
}
});
// CONTROLLER
App.MessagesPageController = Ember.ArrayController.extend({
});
App.Router.map(function(){
this.resource('messages', { path: '/messages'}, function(){
this.route('page', { path: ':num' });
});
});
@psurase-rpx
Copy link

How have you used this in the handlebars? Also, I have a 'show' routes which conflicts with the page route.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment