8
0

collection.js 2.2 KB

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