emittermixin.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. /**
  2. * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module utils/dom/emittermixin
  7. */
  8. import { default as EmitterMixin, _getEmitterListenedTo, _setEmitterId } from '../emittermixin';
  9. import uid from '../uid';
  10. import extend from '../lib/lodash/extend';
  11. import isDomNode from './isdomnode';
  12. /**
  13. * Mixin that injects the DOM events API into its host. It provides the API
  14. * compatible with {@link module:utils/emittermixin~EmitterMixin}.
  15. *
  16. * DOM emitter mixin is by default available in the {@link module:ui/view~View} class,
  17. * but it can also be mixed into any other class:
  18. *
  19. * import mix from '../utils/mix.js';
  20. * import DomEmitterMixin from '../utils/dom/emittermixin.js';
  21. *
  22. * class SomeView {}
  23. * mix( SomeView, DomEmitterMixin );
  24. *
  25. * const view = new SomeView();
  26. * view.listenTo( domElement, ( evt, domEvt ) => {
  27. * console.log( evt, domEvt );
  28. * } );
  29. *
  30. * @mixin module:utils/dom/emittermixin~EmitterMixin
  31. * @mixes module:utils/emittermixin~EmitterMixin
  32. * @implements module:utils/dom/emittermixin~Emitter
  33. */
  34. const DomEmitterMixin = extend( {}, EmitterMixin, {
  35. /**
  36. * Registers a callback function to be executed when an event is fired in a specific Emitter or DOM Node.
  37. * It is backwards compatible with {@link module:utils/emittermixin~EmitterMixin#listenTo}.
  38. *
  39. * @method module:utils/dom/emittermixin~EmitterMixin#listenTo
  40. * @param {module:utils/emittermixin~Emitter|Node} emitter The object that fires the event.
  41. * @param {String} event The name of the event.
  42. * @param {Function} callback The function to be called on event.
  43. * @param {Object} [options={}] Additional options.
  44. * @param {module:utils/priorities~PriorityString|Number} [options.priority='normal'] The priority of this event callback. The higher
  45. * the priority value the sooner the callback will be fired. Events having the same priority are called in the
  46. * order they were added.
  47. * @param {Boolean} [options.useCapture=false] Indicates that events of this type will be dispatched to the registered
  48. * listener before being dispatched to any EventTarget beneath it in the DOM tree.
  49. */
  50. listenTo( emitter, ...rest ) {
  51. // Check if emitter is an instance of DOM Node. If so, replace the argument with
  52. // corresponding ProxyEmitter (or create one if not existing).
  53. if ( isDomNode( emitter ) ) {
  54. const proxy = this._getProxyEmitter( emitter ) || new ProxyEmitter( emitter );
  55. proxy.attach( ...rest );
  56. emitter = proxy;
  57. }
  58. // Execute parent class method with Emitter (or ProxyEmitter) instance.
  59. EmitterMixin.listenTo.call( this, emitter, ...rest );
  60. },
  61. /**
  62. * Stops listening for events. It can be used at different levels:
  63. * It is backwards compatible with {@link module:utils/emittermixin~EmitterMixin#listenTo}.
  64. *
  65. * * To stop listening to a specific callback.
  66. * * To stop listening to a specific event.
  67. * * To stop listening to all events fired by a specific object.
  68. * * To stop listening to all events fired by all object.
  69. *
  70. * @method module:utils/dom/emittermixin~EmitterMixin#stopListening
  71. * @param {module:utils/emittermixin~Emitter|Node} [emitter] The object to stop listening to. If omitted, stops it for all objects.
  72. * @param {String} [event] (Requires the `emitter`) The name of the event to stop listening to. If omitted, stops it
  73. * for all events from `emitter`.
  74. * @param {Function} [callback] (Requires the `event`) The function to be removed from the call list for the given
  75. * `event`.
  76. */
  77. stopListening( emitter, event, callback ) {
  78. // Check if emitter is an instance of DOM Node. If so, replace the argument with corresponding ProxyEmitter.
  79. if ( isDomNode( emitter ) ) {
  80. const proxy = this._getProxyEmitter( emitter );
  81. // Element has no listeners.
  82. if ( !proxy ) {
  83. return;
  84. }
  85. emitter = proxy;
  86. }
  87. // Execute parent class method with Emitter (or ProxyEmitter) instance.
  88. EmitterMixin.stopListening.call( this, emitter, event, callback );
  89. if ( emitter instanceof ProxyEmitter ) {
  90. emitter.detach( event );
  91. }
  92. },
  93. /**
  94. * Retrieves ProxyEmitter instance for given DOM Node residing in this Host.
  95. *
  96. * @param {Node} node DOM Node of the ProxyEmitter.
  97. * @method module:utils/dom/emittermixin~EmitterMixin#_getProxyEmitter
  98. * @return {module:utils/dom/emittermixin~ProxyEmitter} ProxyEmitter instance or null.
  99. */
  100. _getProxyEmitter( node ) {
  101. return _getEmitterListenedTo( this, getNodeUID( node ) );
  102. }
  103. } );
  104. export default DomEmitterMixin;
  105. /**
  106. * Creates a ProxyEmitter instance. Such an instance is a bridge between a DOM Node firing events
  107. * and any Host listening to them. It is backwards compatible with {@link module:utils/emittermixin~EmitterMixin#on}.
  108. *
  109. * listenTo( click, ... )
  110. * +-----------------------------------------+
  111. * | stopListening( ... ) |
  112. * +----------------------------+ | addEventListener( click, ... )
  113. * | Host | | +---------------------------------------------+
  114. * +----------------------------+ | | removeEventListener( click, ... ) |
  115. * | _listeningTo: { | +----------v-------------+ |
  116. * | UID: { | | ProxyEmitter | |
  117. * | emitter: ProxyEmitter, | +------------------------+ +------------v----------+
  118. * | callbacks: { | | events: { | | Node (HTMLElement) |
  119. * | click: [ callbacks ] | | click: [ callbacks ] | +-----------------------+
  120. * | } | | }, | | data-ck-expando: UID |
  121. * | } | | _domNode: Node, | +-----------------------+
  122. * | } | | _domListeners: {}, | |
  123. * | +------------------------+ | | _emitterId: UID | |
  124. * | | DomEmitterMixin | | +--------------^---------+ |
  125. * | +------------------------+ | | | |
  126. * +--------------^-------------+ | +---------------------------------------------+
  127. * | | click (DOM Event)
  128. * +-----------------------------------------+
  129. * fire( click, DOM Event )
  130. *
  131. * @mixes module:utils/emittermixin~EmitterMixin
  132. * @implements module:utils/dom/emittermixin~Emitter
  133. * @private
  134. */
  135. class ProxyEmitter {
  136. /**
  137. * @param {Node} node DOM Node that fires events.
  138. * @returns {Object} ProxyEmitter instance bound to the DOM Node.
  139. */
  140. constructor( node ) {
  141. // Set emitter ID to match DOM Node "expando" property.
  142. _setEmitterId( this, getNodeUID( node ) );
  143. // Remember the DOM Node this ProxyEmitter is bound to.
  144. this._domNode = node;
  145. }
  146. }
  147. extend( ProxyEmitter.prototype, EmitterMixin, {
  148. /**
  149. * Collection of native DOM listeners.
  150. *
  151. * @private
  152. * @member {Object} module:utils/dom/emittermixin~ProxyEmitter#_domListeners
  153. */
  154. /**
  155. * Registers a callback function to be executed when an event is fired.
  156. *
  157. * It attaches a native DOM listener to the DOM Node. When fired,
  158. * a corresponding Emitter event will also fire with DOM Event object as an argument.
  159. *
  160. * @method module:utils/dom/emittermixin~ProxyEmitter#on
  161. * @param {String} event The name of the event.
  162. * @param {Function} callback The function to be called on event.
  163. * @param {Object} [options={}] Additional options.
  164. * @param {Boolean} [options.useCapture=false] Indicates that events of this type will be dispatched to the registered
  165. * listener before being dispatched to any EventTarget beneath it in the DOM tree.
  166. */
  167. attach( event, callback, options = {} ) {
  168. // If the DOM Listener for given event already exist it is pointless
  169. // to attach another one.
  170. if ( this._domListeners && this._domListeners[ event ] ) {
  171. return;
  172. }
  173. const domListener = this._createDomListener( event, !!options.useCapture );
  174. // Attach the native DOM listener to DOM Node.
  175. this._domNode.addEventListener( event, domListener, !!options.useCapture );
  176. if ( !this._domListeners ) {
  177. this._domListeners = {};
  178. }
  179. // Store the native DOM listener in this ProxyEmitter. It will be helpful
  180. // when stopping listening to the event.
  181. this._domListeners[ event ] = domListener;
  182. },
  183. /**
  184. * Stops executing the callback on the given event.
  185. *
  186. * @method module:utils/dom/emittermixin~ProxyEmitter#detach
  187. * @param {String} event The name of the event.
  188. */
  189. detach( event ) {
  190. let events;
  191. // Remove native DOM listeners which are orphans. If no callbacks
  192. // are awaiting given event, detach native DOM listener from DOM Node.
  193. // See: {@link on}.
  194. if ( this._domListeners[ event ] && ( !( events = this._events[ event ] ) || !events.callbacks.length ) ) {
  195. this._domListeners[ event ].removeListener();
  196. }
  197. },
  198. /**
  199. * Creates a native DOM listener callback. When the native DOM event
  200. * is fired it will fire corresponding event on this ProxyEmitter.
  201. * Note: A native DOM Event is passed as an argument.
  202. *
  203. * @private
  204. * @method module:utils/dom/emittermixin~ProxyEmitter#_createDomListener
  205. * @param {String} event The name of the event.
  206. * @param {Boolean} useCapture Indicates whether the listener was created for capturing event.
  207. * @returns {Function} The DOM listener callback.
  208. */
  209. _createDomListener( event, useCapture ) {
  210. const domListener = domEvt => {
  211. this.fire( event, domEvt );
  212. };
  213. // Supply the DOM listener callback with a function that will help
  214. // detach it from the DOM Node, when it is no longer necessary.
  215. // See: {@link off}.
  216. domListener.removeListener = () => {
  217. this._domNode.removeEventListener( event, domListener, useCapture );
  218. delete this._domListeners[ event ];
  219. };
  220. return domListener;
  221. }
  222. } );
  223. // Gets an unique DOM Node identifier. The identifier will be set if not defined.
  224. //
  225. // @private
  226. // @param {Node} node
  227. // @return {String} UID for given DOM Node.
  228. function getNodeUID( node ) {
  229. return node[ 'data-ck-expando' ] || ( node[ 'data-ck-expando' ] = uid() );
  230. }
  231. /**
  232. * Interface representing classes which mix in {@link module:utils/dom/emittermixin~EmitterMixin}.
  233. *
  234. * @interface Emitter
  235. */