Skip to content

Instantly share code, notes, and snippets.

@pzuraq
Created November 20, 2013 16:13
Show Gist options
  • Save pzuraq/7565878 to your computer and use it in GitHub Desktop.
Save pzuraq/7565878 to your computer and use it in GitHub Desktop.
/**
@extends Ember.Mixin
Implements common pagination management properties for controllers.
*/
App.PaginationSupport = Ember.Mixin.create({
hasPaginationSupport: true,
total: 0,
page: 1,
perPage: 30,
pageRange: 3,
actions: {
firstPage: function() {
if (this.get('hasNext')) { // hasNext implies hasFirst
this.send('changePage', 1);
}
},
lastPage: function() {
if (this.get('hasNext')) { // hasPrevious implies hasLast
this.send('changePage', this.get('totalPages'));
}
},
nextPage: function() {
if (this.get('hasNext')) {
this.incrementProperty('page');
}
},
previousPage: function() {
if (this.get('hasPrevious')) {
this.decrementProperty('page');
}
},
changePage: function(page) {
if(page != this.get('page')) {
this.set('page', page);
}
},
changePerPage: function(perPage) {
this.set('perPage', perPage);
this.send('firstPage');
},
updatePage: Ember.K
},
pages: function(){
var page = this.get('page'),
totalPages = this.get('totalPages'),
pageRange = this.get('pageRange'),
windowSize = (pageRange * 2) + 1,
pages = [];
if(page) {
var start = page - pageRange,
end = page + pageRange;
if(start < 1) {
start = 1;
end = (start + windowSize > totalPages) ? totalPages : start + windowSize;
}
if(end > totalPages) {
end = totalPages;
start = (end - windowSize < 1) ? 1 : end - windowSize;
}
for(var i = start; i <= end; i++) {
if(i == page) {
pages.push({page: i, active: true});
} else {
pages.push({page: i});
}
}
}
return pages;
}.property('page', 'total'),
totalPages: function() {
return Math.ceil(this.get('total') / this.get('perPage'));
}.property('total', 'perPage').cacheable(),
hasPrevious: function() {
return this.get('page') > 1;
}.property('page').cacheable(),
hasNext: function() {
return this.get('page') < this.get('totalPages');
}.property('page', 'total').cacheable(),
pageDidChange: function() {
this.send('updatePage');
}.observes('page', 'perPage')
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment