componentfactory.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /**
  2. * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. 'use strict';
  6. import CKEditorError from '../ckeditorerror.js';
  7. /**
  8. * Class implementing the UI component factory.
  9. *
  10. * Factories of specific UI components can be registered under their unique names. Registered
  11. * components can be later instantiated by providing the name of the component. The model is shared between all
  12. * instances of that component and has to be provided upon registering its factory.
  13. *
  14. * The main use case for the component factory is the {@link core.editorUI.EditorUI#featureComponents} factory.
  15. *
  16. * @memberOf core.ui
  17. */
  18. export default class ComponentFactory {
  19. /**
  20. * Creates ComponentFactory instance.
  21. *
  22. * @constructor
  23. * @param {core.Editor} editor The editor instance.
  24. */
  25. constructor( editor ) {
  26. /**
  27. * @readonly
  28. * @member {core.Editor} core.ui.ComponentFactory#editor
  29. */
  30. this.editor = editor;
  31. /**
  32. * Registered component factories.
  33. *
  34. * @private
  35. * @member {Map} core.ui.ComponentFactory#_components
  36. */
  37. this._components = new Map();
  38. }
  39. /**
  40. * Registers a component factory.
  41. *
  42. * @param {String} name The name of the component.
  43. * @param {Function} ControllerClass The component controller constructor.
  44. * @param {Function} ViewClass The component view constructor.
  45. * @param {core.ui.Model} model The model of the component.
  46. */
  47. add( name, ControllerClass, ViewClass, model ) {
  48. if ( this._components.get( name ) ) {
  49. throw new CKEditorError(
  50. 'componentfactory-item-exists: The item already exists in the component factory.', { name }
  51. );
  52. }
  53. this._components.set( name, {
  54. ControllerClass,
  55. ViewClass,
  56. model
  57. } );
  58. }
  59. /**
  60. * Creates a component instance.
  61. *
  62. * @param {String} name The name of the component.
  63. * @returns {core.ui.Controller} The instantiated component.
  64. */
  65. create( name ) {
  66. const component = this._components.get( name );
  67. const model = component.model;
  68. const view = new component.ViewClass( model );
  69. const controller = new component.ControllerClass( model, view, this.editor );
  70. return controller;
  71. }
  72. }