PageRenderTime 20ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/js/utils/collection-paged.js

https://github.com/encryb/encryb.github.io
JavaScript | 85 lines | 63 code | 13 blank | 9 comment | 6 complexity | 69d8c7b5ce7ff99ac293c8f2bee82761 MD5 | raw file
  1. define([
  2. 'backbone'
  3. ],function(Backbone) {
  4. var PagedCollection = Backbone.Collection.extend({
  5. initialize: function(models, options) {
  6. this._limit = options.limit;
  7. this.comparator = options.comparator;
  8. this.setCollection(options.collection);
  9. },
  10. setCollection: function(collection) {
  11. this._collection = collection;
  12. this._collection.on("add", this.onAdd, this);
  13. this._collection.on("remove", this.onRemove, this);
  14. this._collection.on("reset", this.onReset, this);
  15. this._process();
  16. },
  17. increaseLimit: function(increase) {
  18. this._limit = increase + this._limit;
  19. this._process();
  20. },
  21. _process: function() {
  22. // we are at limit
  23. if (this.length >= this._limit) {
  24. return true;
  25. }
  26. // we already have all items
  27. if (this.length >= this._collection.length) {
  28. return false;
  29. }
  30. for (var i = this.length; i < this._collection.length; i++) {
  31. var model = this._collection.at(i);
  32. Backbone.Collection.prototype.add.call(this, model);
  33. // we are at limit
  34. if (this.length >= this._limit) {
  35. return true;
  36. }
  37. }
  38. },
  39. add: function() {
  40. throw "This is a read only collection";
  41. },
  42. remove: function() {
  43. throw "This is a read only collection";
  44. },
  45. reset: function() {
  46. throw "This is a read only collection";
  47. },
  48. /*
  49. * Event handlers
  50. */
  51. onAdd: function(model) {
  52. // if we are at the limit and last element is higher rated than
  53. // new one, don't do anything
  54. if (this.length >= this._limit) {
  55. var lastModel = this.at(this._limit - 1);
  56. if (this.comparator(lastModel) < this.comparator(model)) {
  57. return;
  58. }
  59. }
  60. // else add it to collection
  61. Backbone.Collection.prototype.add.call(this, model);
  62. },
  63. onRemove: function(model) {
  64. Backbone.Collection.prototype.remove.call(this, model);
  65. },
  66. onReset: function() {
  67. var models = this._collection.models.slice(0, this._limit);
  68. Backbone.Collection.prototype.apply.call(this, models);
  69. }
  70. });
  71. return PagedCollection;
  72. });