Skip to content

Instantly share code, notes, and snippets.

@tstolpestad
Forked from io41/paginated_collection.js
Created June 7, 2013 14:23
Show Gist options
  • Select an option

  • Save tstolpestad/5729624 to your computer and use it in GitHub Desktop.

Select an option

Save tstolpestad/5729624 to your computer and use it in GitHub Desktop.
// includes bindings for fetching/fetched
PaginatedCollection = Backbone.Collection.extend({
initialize: function() {
_.bindAll(this, 'parse', 'url', 'nextPage', 'previousPage');
this.page = 1;
},
fetch: function(options) {
options || (options = {});
this.trigger("fetching");
var self = this;
var success = options.success;
options.success = function(resp) {
self.trigger("fetched");
if(success) { success(self, resp); }
};
Backbone.Collection.prototype.fetch.call(this, options);
},
parse: function(resp) {
this.page = resp.page;
this.perPage = resp.per_page;
this.total = resp.total;
return resp.models;
},
url: function() {
return this.base_url + '?' + $.param({page: this.page});
},
nextPage: function() {
this.page = this.page + 1;
this.fetch();
},
previousPage: function() {
this.page = this.page - 1;
this.fetch();
}
});
PaginatedView = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'get_previous', 'get_next', 'render');
this.collection.bind('refresh', this.render);
},
events: {
'click a.prev': 'previous',
'click a.next': 'next'
},
render: function() {
var page_info = {};
page_info.total = this.collection.total;
page_info.page = this.collection.page;
page_info.perPage = this.collection.perPage;
page_info.pages = Math.ceil(page_info.total / page_info.perPage);
var max = Math.min(page_info.total, page_info.page * page_info.perPage);
if(page_info.total == page_info.pages * page_info.perPage) {
max = page_info.total;
}
page_info.range = [(page_info.page - 1) * page_info.perPage + 1, max];
if(page_info.page > 1) {
page_info.prev = page_info.page - 1;
}
else { page_info.prev = false; }
if(page_info.page < page_info.pages) {
page_info.next = page_info.page + 1;
}
else { page_info.next = false; }
this.el.html(JST.pagination(page_info));
},
previous: function() {
this.collection.previousPage();
return false;
},
next: function() {
this.collection.nextPage();
return false;
}
});
<% if(pages > 1) { %>
<% if(prev) { %>
<a href="#" class="prev">previous</a>
<% } else { %>
<span>previous</span>
<% } %>
<%= range[0] %>..<%= range[1] %> of <%= total %>
<% if(next) { %>
<a href="#" class="next">next</a>
<% } else { %>
<span>next</span>
<% } %>
<% } %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment