Skip to content

Instantly share code, notes, and snippets.

@zerowidth
Created November 18, 2010 22:04
Show Gist options
  • Select an option

  • Save zerowidth/705733 to your computer and use it in GitHub Desktop.

Select an option

Save zerowidth/705733 to your computer and use it in GitHub Desktop.
first whack at pagination with backbone.js
// includes bindings for fetching/fetched
PaginatedCollection = Backbone.Collection.extend({
initialize: function() {
_.bindAll(this, 'parse', 'url', 'pageInfo', '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});
},
pageInfo: function() {
var info = {
total: this.total,
page: this.page,
perPage: this.perPage,
pages: Math.ceil(this.total / this.perPage),
prev: false,
next: false
};
var max = Math.min(this.total, this.page * this.perPage);
if (this.total == this.pages * this.perPage) {
max = this.total;
}
info.range = [(this.page - 1) * this.perPage + 1, max];
if (this.page > 1) {
info.prev = this.page - 1;
}
if (this.page < info.pages) {
info.next = this.page + 1;
}
return info;
},
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() {
this.el.html(app.templates.pagination(this.collection.pageInfo()));
},
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>
<% } %>
<% } %>
@dtudury

dtudury commented Aug 20, 2013

Copy link
Copy Markdown

good stuff, ty!

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