model.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /**
  2. * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. 'use strict';
  6. /**
  7. * The base MVC model class.
  8. *
  9. * @class Model
  10. * @mixins Emitter
  11. */
  12. CKEDITOR.define( [ 'emitter', 'utils' ], function( EmitterMixin, utils ) {
  13. /**
  14. * Creates a new Model instance.
  15. *
  16. * @param {Object} [attributes] The model state attributes to be set during the instance creation.
  17. * @param {Object} [properties] The properties to be appended to the instance during creation.
  18. * @method constructor
  19. */
  20. function Model( attributes, properties ) {
  21. /**
  22. * The internal hash containing the model's state.
  23. *
  24. * @property _attributes
  25. * @private
  26. */
  27. Object.defineProperty( this, '_attributes', {
  28. value: {}
  29. } );
  30. // Extend this instance with the additional (out of state) properties.
  31. if ( properties ) {
  32. utils.extend( this, properties );
  33. }
  34. // Initialize the attributes.
  35. if ( attributes ) {
  36. this.set( attributes );
  37. }
  38. }
  39. utils.extend( Model.prototype, EmitterMixin, {
  40. /**
  41. * Creates and sets the value of a model property of this object. This property will be part of the model state
  42. * and are observable.
  43. *
  44. * It accepts also a single object literal containing key/value pairs with properties to be set.
  45. *
  46. * @param {String} name The property name.
  47. * @param {*} value The property value.
  48. */
  49. set: function( name, value ) {
  50. // If the first parameter is an Object, we gonna interact through its properties.
  51. if ( utils.isObject( name ) ) {
  52. Object.keys( name ).forEach( function( attr ) {
  53. this.set( attr, name[ attr ] );
  54. }, this );
  55. return;
  56. }
  57. Object.defineProperty( this, name, {
  58. enumerable: true,
  59. configurable: true,
  60. get: function() {
  61. return this._attributes[ name ];
  62. },
  63. set: function( value ) {
  64. var oldValue = this._attributes[ name ];
  65. if ( oldValue !== value ) {
  66. this._attributes[ name ] = value;
  67. this.fire( 'change', this, name, value, oldValue );
  68. this.fire( 'change:' + name, this, value, oldValue );
  69. }
  70. }
  71. } );
  72. this[ name ] = value;
  73. }
  74. } );
  75. return Model;
  76. } );