PageRenderTime 57ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/javascript/shared-package/backbone-extensions.js

https://bitbucket.org/lmeius/lehor
JavaScript | 87 lines | 71 code | 8 blank | 8 comment | 12 complexity | e7474195ba3c0566c786bf5b3baba011 MD5 | raw file
Possible License(s): MIT, BSD-3-Clause, CC-BY-3.0, GPL-3.0
  1. // This file contains extensions to Backbone models, collections, etc. that can
  2. // be reused throughout the codebase, as well as any global overrides.
  3. /* Backbone.Collection has no facility to asynchronously fetch individual
  4. models. IncrementalCollection.fetchByID() will return the given model
  5. if it is already loaded from the server, or fetch it immediately. The
  6. callback is called either immediately or when the model is finished
  7. loading. The __inited flag on the model is set to true if the model
  8. has been loaded from the server. */
  9. window.IncrementalCollection = Backbone.Collection.extend({
  10. fetchByID: function(id, callback, args) {
  11. var ret = this.get(id);
  12. if (!ret) {
  13. if (!this.idAttribute) {
  14. this.idAttribute = this.model.prototype.idAttribute;
  15. if (!this.idAttribute) {
  16. this.idAttribute = "id";
  17. }
  18. }
  19. var attrs = {};
  20. attrs[this.idAttribute] = id;
  21. ret = this._add(attrs);
  22. }
  23. if (!ret.__inited) {
  24. if (!ret.__callbacks) {
  25. ret.__callbacks = [];
  26. }
  27. if (callback) {
  28. ret.__callbacks.push({ callback: callback, args: args });
  29. }
  30. if (!ret.__requesting) {
  31. KAConsole.log("IC (" + id + "): Sending request...");
  32. ret.fetch({
  33. success: function() {
  34. KAConsole.log("IC (" + id + "): Request succeeded.");
  35. ret.__inited = true;
  36. ret.__requesting = false;
  37. _.each(ret.__callbacks, function(cb) {
  38. cb.callback.apply(null, [ret].concat(cb.args));
  39. });
  40. ret.__callbacks = [];
  41. },
  42. error: function() {
  43. KAConsole.log("IC (" + id + "): Request failed!");
  44. ret.__requesting = false;
  45. }
  46. });
  47. ret.__requesting = true;
  48. } else {
  49. KAConsole.log("IC (" + id + "): Already requested.");
  50. }
  51. } else {
  52. KAConsole.log("IC (" + id + "): Already loaded.");
  53. if (callback) {
  54. callback.apply(null, [ret].concat(args));
  55. }
  56. }
  57. return ret;
  58. },
  59. resetInited: function(models, options) {
  60. this.reset(models, options);
  61. _.each(this.models, function(model) {
  62. model.__inited = true;
  63. });
  64. },
  65. addInited: function(models, options) {
  66. if (!this.idAttribute) {
  67. this.idAttribute = new this.model({}).idAttribute;
  68. if (!this.idAttribute) {
  69. this.idAttribute = "id";
  70. }
  71. }
  72. var self = this;
  73. this.add(models, options);
  74. _.each(models, function(model) {
  75. var newModel = self.get(model[self.idAttribute]);
  76. newModel.__inited = true;
  77. });
  78. }
  79. });