collection.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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. * Collections are ordered sets of models.
  8. *
  9. * Any event that is triggered on a model in a collection will also be triggered on the collection directly, for
  10. * convenience.
  11. *
  12. * @class Collection
  13. */
  14. CKEDITOR.define( [ 'emitter', 'utils' ], function( EmitterMixin, utils ) {
  15. function Collection() {
  16. /**
  17. * The internal list of models in the collection.
  18. *
  19. * @property _models
  20. * @private
  21. */
  22. Object.defineProperty( this, '_models', {
  23. value: []
  24. } );
  25. /**
  26. * The number of items available in the collection.
  27. *
  28. * @property length
  29. */
  30. Object.defineProperty( this, 'length', {
  31. get: function() {
  32. return this._models.length;
  33. }
  34. } );
  35. }
  36. /**
  37. * @inheritdoc utils#extend
  38. */
  39. Collection.extend = utils.extendMixin;
  40. utils.extend( Collection.prototype, EmitterMixin, {
  41. /**
  42. * Adds an item into the collection.
  43. *
  44. * Note that this is an array-like collection, so the same item can be present more than once. This behavior is
  45. * for performance purposes only and is not guaranteed to be kept in the same way in the future.
  46. *
  47. * @param {Model} model The item to be added.
  48. */
  49. add: function( model ) {
  50. this._models.push( model );
  51. this.fire( 'add', model );
  52. },
  53. /**
  54. * Gets one item from the collection.
  55. *
  56. * @param {Number} index The index to take the item from.
  57. * @returns {Model} The requested item.
  58. */
  59. get: function( index ) {
  60. var model = this._models[ index ];
  61. if ( !model ) {
  62. throw new Error( 'Index not found' );
  63. }
  64. return model;
  65. },
  66. /**
  67. * Removes an item from the collection.
  68. *
  69. * @param {Model|Number} modelOrIndex Either the item itself or its index inside the collection.
  70. * @returns {Model} The removed item.
  71. */
  72. remove: function( modelOrIndex ) {
  73. // If a model has been passed, convert it to its index.
  74. if ( typeof modelOrIndex != 'number' ) {
  75. modelOrIndex = this._models.indexOf( modelOrIndex );
  76. if ( modelOrIndex == -1 ) {
  77. throw new Error( 'Model not found' );
  78. }
  79. }
  80. var removedModel = this._models.splice( modelOrIndex, 1 )[ 0 ];
  81. if ( !removedModel ) {
  82. throw new Error( 'Index not found' );
  83. }
  84. this.fire( 'remove', removedModel );
  85. return removedModel;
  86. }
  87. } );
  88. return Collection;
  89. } );