Guest User

Untitled

a guest
Jan 24th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. // includes bindings for fetching/fetched
  2.  
  3. var PaginatedCollection = Backbone.Collection.extend({
  4. baseUrl: '/items', // set this to your restful route on the server
  5.  
  6. initialize: function() {
  7. _.bindAll(this, 'parse', 'url', 'pageInfo', 'nextPage', 'previousPage');
  8. typeof(options) != 'undefined' || (options = {});
  9. this.page = 1;
  10. typeof(this.perPage) != 'undefined' || (this.perPage = 10);
  11. },
  12. fetch: function(options) {
  13. typeof(options) != 'undefined' || (options = {});
  14. this.trigger("fetching");
  15. var self = this;
  16. var success = options.success;
  17. options.success = function(resp) {
  18. self.trigger("fetched");
  19. if(success) { success(self, resp); }
  20. };
  21. return Backbone.Collection.prototype.fetch.call(this, options);
  22. },
  23. parse: function(resp) {
  24. this.page = resp.page;
  25. this.perPage = resp.perPage;
  26. this.total = resp.total;
  27. return resp.models;
  28. },
  29. url: function() {
  30. return this.baseUrl + '?' + $.param({page: this.page, perPage: this.perPage});
  31. },
  32. pageInfo: function() {
  33. var info = {
  34. total: this.total,
  35. page: this.page,
  36. perPage: this.perPage,
  37. pages: Math.ceil(this.total / this.perPage),
  38. prev: false,
  39. next: false
  40. };
  41.  
  42. var max = Math.min(this.total, this.page * this.perPage);
  43.  
  44. if (this.total == this.pages * this.perPage) {
  45. max = this.total;
  46. }
  47.  
  48. info.range = [(this.page - 1) * this.perPage + 1, max];
  49.  
  50. if (this.page > 1) {
  51. info.prev = this.page - 1;
  52. }
  53.  
  54. if (this.page < info.pages) {
  55. info.next = this.page + 1;
  56. }
  57.  
  58. return info;
  59. },
  60. nextPage: function() {
  61. if (!this.pageInfo().next) {
  62. return false;
  63. }
  64. this.page = this.page + 1;
  65. return this.fetch();
  66. },
  67. previousPage: function() {
  68. if (!this.pageInfo().prev) {
  69. return false;
  70. }
  71. this.page = this.page - 1;
  72. return this.fetch();
  73. }
  74.  
  75. });
Add Comment
Please, Sign In to add comment