Guest User

Untitled

a guest
Nov 21st, 2018
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. //
  2. // Backbone.PagedCollection
  3. //
  4. // A smarter way to consume list resources over HTTP. Call it Hypermedia, REST,
  5. // whatever. There are other problems that we may wish to solve with the
  6. // current implementation of PagedCollection:
  7. //
  8. // 1. Jumping between specific pages;
  9. // 2. Web Linking works, however `per_page` paramter must be implemented;
  10. // 3. Call to `fetch` is required to retreive Link field, which means bootstrapping is a problem; and
  11. // 4. `parser.js` which is used to parse Link field is too big. May have to move off PEG.js version.
  12. //
  13. // @depends on parser.js which was generated via PEG.js to parse Link-field in the HTTP response header.
  14. //
  15.  
  16. Backbone.PagedCollection = (function (parser) {
  17.  
  18. var find = function (link, type) {
  19. return _.find(link || [], function (value) {
  20. return value.rel == type;
  21. });
  22. };
  23.  
  24. var PagedCollection = Backbone.Collection.extend({
  25. parse: function (response, xhr) {
  26. var link = xhr.getResponseHeader('Link');
  27.  
  28. if (link) {
  29. this.link = parser.parse(link);
  30. }
  31.  
  32. return Backbone.Collection.prototype.parse.apply(this, arguments);
  33. },
  34.  
  35. // Jump to a given related link as specified by the `rel` attribute.
  36.  
  37. jump: function (type, options) {
  38. var link = find(this.link, type);
  39. if (link && link.href) {
  40. this.url = link.href;
  41. return this.fetch(options);
  42. }
  43. }
  44. });
  45.  
  46. // As a collection, the only type of related links that we care about are the
  47. // the following 4 methods. You can use `jump` directly, however types such as
  48. // `document`, `external` won't make sense in this context. We can probably
  49. // make `Backbone.Model` smarter as well using similar Web Linking techniques
  50. // however, that is not part of this exercise.
  51.  
  52. _.each(['first', 'prev', 'next', 'last'], function (method) {
  53. PagedCollection.prototype[method] = function (options) {
  54. return this.jump(method, options);
  55. };
  56. });
  57.  
  58. return PagedCollection;
  59.  
  60. }(parser));
Add Comment
Please, Sign In to add comment