emittermixin.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. /**
  2. * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module utils/emittermixin
  7. */
  8. import EventInfo from './eventinfo.js';
  9. import uid from './uid.js';
  10. import priorities from './priorities.js';
  11. /**
  12. * Mixin that injects the events API into its host.
  13. *
  14. * @mixin EmitterMixin
  15. * @implements module:utils/emittermixin~Emitter
  16. */
  17. const EmitterMixin = {
  18. /**
  19. * Registers a callback function to be executed when an event is fired. Events can be grouped in namespaces using `:`.
  20. * When namespaced event is fired, it additionaly fires all callbacks for that namespace.
  21. *
  22. * myEmitter.on( 'myGroup', genericCallback );
  23. * myEmitter.on( 'myGroup:myEvent', specificCallback );
  24. * myEmitter.fire( 'myGroup' ); // genericCallback is fired.
  25. * myEmitter.fire( 'myGroup:myEvent' ); // both genericCallback and specificCallback are fired.
  26. * myEmitter.fire( 'myGroup:foo' ); // genericCallback is fired even though there are no callbacks for "foo".
  27. *
  28. * @param {String} event The name of the event.
  29. * @param {Function} callback The function to be called on event.
  30. * @param {Object} [options={}] Additional options.
  31. * @param {module:utils/priorities~PriorityString|Number} [options.priority='normal'] The priority of this event callback. The higher
  32. * the priority value the sooner the callback will be fired. Events having the same priority are called in the
  33. * order they were added.
  34. * -+
  35. * @param {Object} [options.context] The object that represents `this` in the callback. Defaults to the object firing the event.
  36. * @method #on
  37. */
  38. on( event, callback, options = {} ) {
  39. createEventNamespace( this, event );
  40. const lists = getCallbacksListsForNamespace( this, event );
  41. const priority = priorities.get( options.priority );
  42. callback = {
  43. callback: callback,
  44. context: options.context || this,
  45. priority: priority
  46. };
  47. // Add the callback to all callbacks list.
  48. for ( let callbacks of lists ) {
  49. // Add the callback to the list in the right priority position.
  50. let added = false;
  51. for ( let i = 0; i < callbacks.length; i++ ) {
  52. if ( callbacks[ i ].priority < priority ) {
  53. callbacks.splice( i, 0, callback );
  54. added = true;
  55. break;
  56. }
  57. }
  58. // Add at the end, if right place was not found.
  59. if ( !added ) {
  60. callbacks.push( callback );
  61. }
  62. }
  63. },
  64. /**
  65. * Registers a callback function to be executed on the next time the event is fired only. This is similar to
  66. * calling {@link #on} followed by {@link #off} in the callback.
  67. *
  68. * @param {String} event The name of the event.
  69. * @param {Function} callback The function to be called on event.
  70. * @param {Object} [options={}] Additional options.
  71. * @param {module:utils/priorities~PriorityString|Number} [options.priority='normal'] The priority of this event callback. The higher
  72. * the priority value the sooner the callback will be fired. Events having the same priority are called in the
  73. * order they were added.
  74. * @param {Object} [options.context] The object that represents `this` in the callback. Defaults to the object firing the event.
  75. * @method #once
  76. */
  77. once( event, callback, options ) {
  78. const onceCallback = function( event ) {
  79. // Go off() at the first call.
  80. event.off();
  81. // Go with the original callback.
  82. callback.apply( this, arguments );
  83. };
  84. // Make a similar on() call, simply replacing the callback.
  85. this.on( event, onceCallback, options );
  86. },
  87. /**
  88. * Stops executing the callback on the given event.
  89. *
  90. * @param {String} event The name of the event.
  91. * @param {Function} callback The function to stop being called.
  92. * @param {Object} [context] The context object to be removed, pared with the given callback. To handle cases where
  93. * the same callback is used several times with different contexts.
  94. * @method #off
  95. */
  96. off( event, callback, context ) {
  97. const lists = getCallbacksListsForNamespace( this, event );
  98. for ( let callbacks of lists ) {
  99. for ( let i = 0; i < callbacks.length; i++ ) {
  100. if ( callbacks[ i ].callback == callback ) {
  101. if ( !context || context == callbacks[ i ].context ) {
  102. // Remove the callback from the list (fixing the next index).
  103. callbacks.splice( i, 1 );
  104. i--;
  105. }
  106. }
  107. }
  108. }
  109. },
  110. /**
  111. * Registers a callback function to be executed when an event is fired in a specific (emitter) object.
  112. *
  113. * @param {module:utils/emittermixin~Emitter} emitter The object that fires the event.
  114. * @param {String} event The name of the event.
  115. * @param {Function} callback The function to be called on event.
  116. * @param {Object} [options={}] Additional options.
  117. * @param {module:utils/priorities~PriorityString|Number} [options.priority='normal'] The priority of this event callback. The higher
  118. * the priority value the sooner the callback will be fired. Events having the same priority are called in the
  119. * order they were added.
  120. * @param {Object} [options.context] The object that represents `this` in the callback. Defaults to the object firing the event.
  121. * @method #listenTo
  122. */
  123. listenTo( emitter, event, callback, options ) {
  124. let emitters, emitterId, emitterInfo, eventCallbacks;
  125. // _listeningTo contains a list of emitters that this object is listening to.
  126. // This list has the following format:
  127. //
  128. // _listeningTo: {
  129. // emitterId: {
  130. // emitter: emitter,
  131. // callbacks: {
  132. // event1: [ callback1, callback2, ... ]
  133. // ....
  134. // }
  135. // },
  136. // ...
  137. // }
  138. if ( !( emitters = this._listeningTo ) ) {
  139. emitters = this._listeningTo = {};
  140. }
  141. if ( !( emitterId = emitter._emitterId ) ) {
  142. emitterId = emitter._emitterId = uid();
  143. }
  144. if ( !( emitterInfo = emitters[ emitterId ] ) ) {
  145. emitterInfo = emitters[ emitterId ] = {
  146. emitter: emitter,
  147. callbacks: {}
  148. };
  149. }
  150. if ( !( eventCallbacks = emitterInfo.callbacks[ event ] ) ) {
  151. eventCallbacks = emitterInfo.callbacks[ event ] = [];
  152. }
  153. eventCallbacks.push( callback );
  154. // Finally register the callback to the event.
  155. emitter.on( event, callback, options );
  156. },
  157. /**
  158. * Stops listening for events. It can be used at different levels:
  159. *
  160. * * To stop listening to a specific callback.
  161. * * To stop listening to a specific event.
  162. * * To stop listening to all events fired by a specific object.
  163. * * To stop listening to all events fired by all object.
  164. *
  165. * @param {module:utils/emittermixin~Emitter} [emitter] The object to stop listening to. If omitted, stops it for all objects.
  166. * @param {String} [event] (Requires the `emitter`) The name of the event to stop listening to. If omitted, stops it
  167. * for all events from `emitter`.
  168. * @param {Function} [callback] (Requires the `event`) The function to be removed from the call list for the given
  169. * `event`.
  170. * @method #stopListening
  171. */
  172. stopListening( emitter, event, callback ) {
  173. let emitters = this._listeningTo;
  174. let emitterId = emitter && emitter._emitterId;
  175. let emitterInfo = emitters && emitterId && emitters[ emitterId ];
  176. let eventCallbacks = emitterInfo && event && emitterInfo.callbacks[ event ];
  177. // Stop if nothing has been listened.
  178. if ( !emitters || ( emitter && !emitterInfo ) || ( event && !eventCallbacks ) ) {
  179. return;
  180. }
  181. // All params provided. off() that single callback.
  182. if ( callback ) {
  183. emitter.off( event, callback );
  184. }
  185. // Only `emitter` and `event` provided. off() all callbacks for that event.
  186. else if ( eventCallbacks ) {
  187. while ( ( callback = eventCallbacks.pop() ) ) {
  188. emitter.off( event, callback );
  189. }
  190. delete emitterInfo.callbacks[ event ];
  191. }
  192. // Only `emitter` provided. off() all events for that emitter.
  193. else if ( emitterInfo ) {
  194. for ( event in emitterInfo.callbacks ) {
  195. this.stopListening( emitter, event );
  196. }
  197. delete emitters[ emitterId ];
  198. }
  199. // No params provided. off() all emitters.
  200. else {
  201. for ( emitterId in emitters ) {
  202. this.stopListening( emitters[ emitterId ].emitter );
  203. }
  204. delete this._listeningTo;
  205. }
  206. },
  207. /**
  208. * Fires an event, executing all callbacks registered for it.
  209. *
  210. * The first parameter passed to callbacks is an {@link module:utils/eventinfo~EventInfo} object,
  211. * followed by the optional `args` provided in the `fire()` method call.
  212. *
  213. * @param {String|module:utils/eventinfo~EventInfo} eventOrInfo The name of the event or `EventInfo` object if event is delegated.
  214. * @param {...*} [args] Additional arguments to be passed to the callbacks.
  215. * @method #fire
  216. */
  217. fire( eventOrInfo, ...args ) {
  218. const eventInfo = eventOrInfo instanceof EventInfo ? eventOrInfo : new EventInfo( this, eventOrInfo );
  219. const event = eventInfo.name;
  220. let callbacks = getCallbacksForEvent( this, event );
  221. // Record that the event passed this emitter on its path.
  222. eventInfo.path.push( this );
  223. // Handle event listener callbacks first.
  224. if ( callbacks ) {
  225. // Arguments passed to each callback.
  226. const callbackArgs = [ eventInfo, ...args ];
  227. // Copying callbacks array is the easiest and most secure way of preventing infinite loops, when event callbacks
  228. // are added while processing other callbacks. Previous solution involved adding counters (unique ids) but
  229. // failed if callbacks were added to the queue before currently processed callback.
  230. // If this proves to be too inefficient, another method is to change `.on()` so callbacks are stored if same
  231. // event is currently processed. Then, `.fire()` at the end, would have to add all stored events.
  232. callbacks = Array.from( callbacks );
  233. for ( let i = 0; i < callbacks.length; i++ ) {
  234. callbacks[ i ].callback.apply( callbacks[ i ].context, callbackArgs );
  235. // Remove the callback from future requests if off() has been called.
  236. if ( eventInfo.off.called ) {
  237. // Remove the called mark for the next calls.
  238. delete eventInfo.off.called;
  239. this.off( event, callbacks[ i ].callback, callbacks[ i ].context );
  240. }
  241. // Do not execute next callbacks if stop() was called.
  242. if ( eventInfo.stop.called ) {
  243. break;
  244. }
  245. }
  246. }
  247. // Delegate event to other emitters if needed.
  248. if ( this._delegations ) {
  249. const destinations = this._delegations.get( event );
  250. if ( destinations ) {
  251. for ( let dest of destinations ) {
  252. dest.fire( eventInfo, ...args );
  253. }
  254. }
  255. }
  256. },
  257. /**
  258. * Delegates selected events to another {@link module:utils/emittermixin~Emitter}. For instance:
  259. *
  260. * emitterA.delegate( 'eventX' ).to( emitterB );
  261. * emitterA.delegate( 'eventX', 'eventY' ).to( emitterC );
  262. *
  263. * then `eventX` is delegated (fired by) `emitterB` and `emitterC` along with `data`:
  264. *
  265. * emitterA.fire( 'eventX', data );
  266. *
  267. * and `eventY` is delegated (fired by) `emitterC` along with `data`:
  268. *
  269. * emitterA.fire( 'eventY', data );
  270. *
  271. * @method #delegate
  272. * @param {...String} events Event names that will be delegated to another emitter.
  273. * @returns {module:utils/emittermixin~EmitterMixin.delegate#to}
  274. */
  275. delegate( ...events ) {
  276. return {
  277. /**
  278. * Selects destination for {@link module:utils/emittermixin~EmitterMixin#delegate} events.
  279. *
  280. * @method module:utils/emittermixin~EmitterMixin.delegate#to
  281. * @param {module:utils/emittermixin~Emitter} emitter An `EmitterMixin` instance which is the destination for delegated events.
  282. */
  283. to: ( emitter ) => {
  284. if ( !this._delegations ) {
  285. this._delegations = new Map();
  286. }
  287. for ( let eventName of events ) {
  288. let destinations = this._delegations.get( eventName );
  289. if ( !destinations ) {
  290. this._delegations.set( eventName, [ emitter ] );
  291. } else {
  292. destinations.push( emitter );
  293. }
  294. }
  295. }
  296. };
  297. },
  298. /**
  299. * Stops delegating events. It can be used at different levels:
  300. *
  301. * * To stop delegating all events.
  302. * * To stop delegating a specific event to all emitters.
  303. * * To stop delegating a specific event to a specific emitter.
  304. *
  305. * @param {String} [event] The name of the event to stop delegating. If omitted, stops it all delegations.
  306. * @param {module:utils/emittermixin~Emitter} [emitter] (requires `event`) The object to stop delegating a particular event to.
  307. * If omitted, stops delegation of `event` to all emitters.
  308. * @method #stopDelegating
  309. */
  310. stopDelegating( event, emitter ) {
  311. if ( !this._delegations ) {
  312. return;
  313. }
  314. if ( !event ) {
  315. this._delegations.clear();
  316. } else if ( !emitter ) {
  317. this._delegations.delete( event );
  318. } else {
  319. const destinations = this._delegations.get( event );
  320. const index = destinations.indexOf( emitter );
  321. if ( index !== -1 ) {
  322. destinations.splice( index, 1 );
  323. }
  324. }
  325. }
  326. };
  327. export default EmitterMixin;
  328. // Gets the internal `_events` property of the given object.
  329. // `_events` property store all lists with callbacks for registered event names.
  330. // If there were no events registered on the object, empty `_events` object is created.
  331. function getEvents( source ) {
  332. if ( !source._events ) {
  333. Object.defineProperty( source, '_events', {
  334. value: {}
  335. } );
  336. }
  337. return source._events;
  338. }
  339. // Creates event node for generic-specific events relation architecture.
  340. function makeEventNode() {
  341. return {
  342. callbacks: [],
  343. childEvents: []
  344. };
  345. }
  346. // Creates an architecture for generic-specific events relation.
  347. // If needed, creates all events for given eventName, i.e. if the first registered event
  348. // is foo:bar:abc, it will create foo:bar:abc, foo:bar and foo event and tie them together.
  349. // It also copies callbacks from more generic events to more specific events when
  350. // specific events are created.
  351. function createEventNamespace( source, eventName ) {
  352. const events = getEvents( source );
  353. // First, check if the event we want to add to the structure already exists.
  354. if ( events[ eventName ] ) {
  355. // If it exists, we don't have to do anything.
  356. return;
  357. }
  358. // In other case, we have to create the structure for the event.
  359. // Note, that we might need to create intermediate events too.
  360. // I.e. if foo:bar:abc is being registered and we only have foo in the structure,
  361. // we need to also register foo:bar.
  362. // Currently processed event name.
  363. let name = eventName;
  364. // Name of the event that is a child event for currently processed event.
  365. let childEventName = null;
  366. // Array containing all newly created specific events.
  367. const newEventNodes = [];
  368. // While loop can't check for ':' index because we have to handle generic events too.
  369. // In each loop, we truncate event name, going from the most specific name to the generic one.
  370. // I.e. foo:bar:abc -> foo:bar -> foo.
  371. while ( name !== '' ) {
  372. if ( events[ name ] ) {
  373. // If the currently processed event name is already registered, we can be sure
  374. // that it already has all the structure created, so we can break the loop here
  375. // as no more events need to be registered.
  376. break;
  377. }
  378. // If this event is not yet registered, create a new object for it.
  379. events[ name ] = makeEventNode();
  380. // Add it to the array with newly created events.
  381. newEventNodes.push( events[ name ] );
  382. // Add previously processed event name as a child of this event.
  383. if ( childEventName ) {
  384. events[ name ].childEvents.push( childEventName );
  385. }
  386. childEventName = name;
  387. // If `.lastIndexOf()` returns -1, `.substr()` will return '' which will break the loop.
  388. name = name.substr( 0, name.lastIndexOf( ':' ) );
  389. }
  390. if ( name !== '' ) {
  391. // If name is not empty, we found an already registered event that was a parent of the
  392. // event we wanted to register.
  393. // Copy that event's callbacks to newly registered events.
  394. for ( let node of newEventNodes ) {
  395. node.callbacks = events[ name ].callbacks.slice();
  396. }
  397. // Add last newly created event to the already registered event.
  398. events[ name ].childEvents.push( childEventName );
  399. }
  400. }
  401. // Gets an array containing callbacks list for a given event and it's more specific events.
  402. // I.e. if given event is foo:bar and there is also foo:bar:abc event registered, this will
  403. // return callback list of foo:bar and foo:bar:abc (but not foo).
  404. // Returns empty array if given event has not been yet registered.
  405. function getCallbacksListsForNamespace( source, eventName ) {
  406. const eventNode = getEvents( source )[ eventName ];
  407. if ( !eventNode ) {
  408. return [];
  409. }
  410. let callbacksLists = [ eventNode.callbacks ];
  411. for ( let i = 0; i < eventNode.childEvents.length; i++ ) {
  412. let childCallbacksLists = getCallbacksListsForNamespace( source, eventNode.childEvents[ i ] );
  413. callbacksLists = callbacksLists.concat( childCallbacksLists );
  414. }
  415. return callbacksLists;
  416. }
  417. // Get the list of callbacks for a given event, but only if there any callbacks have been registered.
  418. // If there are no callbacks registered for given event, it checks if this is a specific event and looks
  419. // for callbacks for it's more generic version.
  420. function getCallbacksForEvent( source, eventName ) {
  421. let event;
  422. if ( !source._events || !( event = source._events[ eventName ] ) || !event.callbacks.length ) {
  423. // There are no callbacks registered for specified eventName.
  424. // But this could be a specific-type event that is in a namespace.
  425. if ( eventName.indexOf( ':' ) > -1 ) {
  426. // If the eventName is specific, try to find callback lists for more generic event.
  427. return getCallbacksForEvent( source, eventName.substr( 0, eventName.lastIndexOf( ':' ) ) );
  428. } else {
  429. // If this is a top-level generic event, return null;
  430. return null;
  431. }
  432. }
  433. return event.callbacks;
  434. }
  435. /**
  436. * Interface representing classes which mix in {@link module:utils/emittermixin~EmitterMixin}.
  437. *
  438. * @interface Emitter
  439. */