lateralus.model.js

  1. import _ from 'lodash-compat';
  2. import Backbone from 'backbone';
  3. import mixins from './lateralus.mixins';
  4. const fn = {};
  5. // jshint maxlen:100
  6. /**
  7. * @private
  8. * @param {Lateralus} lateralus
  9. * @param {Object} [attributes]
  10. * @param {Object} [options]
  11. * @mixes Lateralus.mixins
  12. * @constructs Lateralus.Model
  13. */
  14. fn.constructor = function (lateralus, attributes, options) {
  15. /**
  16. * A reference to the central {@link Lateralus} instance.
  17. * @member Lateralus.Model#lateralus
  18. * @type {Lateralus}
  19. * @final
  20. */
  21. this.lateralus = lateralus;
  22. this.delegateLateralusEvents();
  23. this.on('change', _.bind(this.onChange, this));
  24. Backbone.Model.call(this, attributes, options);
  25. };
  26. /**
  27. * For every key that is changed on this model, a corresponding `change:` event
  28. * is `{@link Lateralus.mixins#emit}`ed. For example, `set`ting the `"foo"`
  29. * attribute will `{@link Lateralus.mixins#emit}` `"change:foo"` and provide
  30. * the changed value.
  31. * @method Lateralus.Model#onChange
  32. */
  33. fn.onChange = function () {
  34. const changed = this.changedAttributes();
  35. _.each(_.keys(changed), (changedKey) => {
  36. this.emit('change:' + changedKey, changed[changedKey]);
  37. // Delete this property from the internal "changed" object before
  38. // Backbone typically would to prevent "stacking" changed properties
  39. // across onChange calls, thereby causing redundant handler calls.
  40. delete this.changed[changedKey];
  41. });
  42. };
  43. _.extend(fn, mixins);
  44. /**
  45. * This class builds on the ideas and APIs of
  46. * [`Backbone.Model`](http://backbonejs.org/#Model). The constructor for
  47. * this class should not be called by application code, it is used by the
  48. * `{@link Lateralus}` constructor.
  49. * @extends Backbone.Model
  50. * @class Lateralus.Model
  51. */
  52. const LateralusModel = Backbone.Model.extend(fn);
  53. /**
  54. * @method Lateralus.Model#toString
  55. * @return {string} The name of this Model. This is used internally by
  56. * Lateralus.
  57. */
  58. LateralusModel.prototype.toString = function () {
  59. return this.lateralus.toString() + '-model';
  60. };
  61. export default LateralusModel;