PageRenderTime 150ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/app/scripts/common/Calcium.js

https://gitlab.com/yutiansut/Strut
JavaScript | 72 lines | 61 code | 6 blank | 5 comment | 11 complexity | eed993c73e2d3819b0b1f00292f2db8c MD5 | raw file
  1. define(["libs/backbone"],
  2. function(Backbone) {
  3. function isModelish(obj) {
  4. return obj instanceof Backbone.Model ||
  5. obj instanceof Backbone.Collection;
  6. }
  7. /**
  8. * @class Calcium.Model
  9. */
  10. var Model = Backbone.Model.extend({
  11. // ugh.. hax w/ the inspectArrays param...
  12. // TODO: we need to detect object loops!!!!!!
  13. toJSON: function(dontRecurse, inspectArrays) {
  14. if (dontRecurse) {
  15. return Backbone.Model.prototype.toJSON.apply(this, arguments);
  16. } else {
  17. var result = {};
  18. for (var attr in this.attributes) {
  19. var obj = this.attributes[attr];
  20. if (isModelish(obj)) {
  21. result[attr] = obj.toJSON(dontRecurse, inspectArrays);
  22. } else if (inspectArrays && obj instanceof Array) {
  23. var resArr = [];
  24. result[attr] = resArr;
  25. obj.forEach(function(elem, idx) {
  26. if (isModelish(elem))
  27. resArr.push(elem.toJSON(dontRecurse, inspectArrays))
  28. else
  29. resArr.push(elem)
  30. });
  31. } else {
  32. result[attr] = obj;
  33. }
  34. }
  35. return result;
  36. }
  37. }
  38. });
  39. var Collection = Backbone.Collection.extend({
  40. toJSON: function(dontRecurse, inspectArrays) {
  41. if (dontRecurse) {
  42. return Backbone.Collection.prototype.toJSON.apply(this, arguments);
  43. } else {
  44. var resArr = [];
  45. this.models.forEach(function(model, idx) {
  46. resArr.push(model.toJSON(dontRecurse, inspectArrays))
  47. });
  48. return resArr;
  49. }
  50. }
  51. });
  52. function Disposable(obj, fn, args) {
  53. this.args = args;
  54. this.obj = obj;
  55. this.fn = fn;
  56. }
  57. Disposable.prototype = {
  58. dispose: function() {
  59. this.fn.apply(this.obj, this.args);
  60. }
  61. };
  62. return {
  63. Model: Model,
  64. Collection: Collection
  65. }
  66. });