EventEmitter.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. /*!
  2. * EventEmitter v4.2.11 - git.io/ee
  3. * Unlicense - http://unlicense.org/
  4. * Oliver Caldwell - http://oli.me.uk/
  5. * @preserve
  6. */
  7. ;(function () {
  8. 'use strict';
  9. /**
  10. * Class for managing events.
  11. * Can be extended to provide event functionality in other classes.
  12. *
  13. * @class EventEmitter Manages event registering and emitting.
  14. */
  15. function EventEmitter() {}
  16. // Shortcuts to improve speed and size
  17. var proto = EventEmitter.prototype;
  18. var exports = this;
  19. var originalGlobalValue = exports.EventEmitter;
  20. /**
  21. * Finds the index of the listener for the event in its storage array.
  22. *
  23. * @param {Function[]} listeners Array of listeners to search through.
  24. * @param {Function} listener Method to look for.
  25. * @return {Number} Index of the specified listener, -1 if not found
  26. * @api private
  27. */
  28. function indexOfListener(listeners, listener) {
  29. var i = listeners.length;
  30. while (i--) {
  31. if (listeners[i].listener === listener) {
  32. return i;
  33. }
  34. }
  35. return -1;
  36. }
  37. /**
  38. * Alias a method while keeping the context correct, to allow for overwriting of target method.
  39. *
  40. * @param {String} name The name of the target method.
  41. * @return {Function} The aliased method
  42. * @api private
  43. */
  44. function alias(name) {
  45. return function aliasClosure() {
  46. return this[name].apply(this, arguments);
  47. };
  48. }
  49. /**
  50. * Returns the listener array for the specified event.
  51. * Will initialise the event object and listener arrays if required.
  52. * Will return an object if you use a regex search. The object contains keys for each matched event. So /ba[rz]/ might return an object containing bar and baz. But only if you have either defined them with defineEvent or added some listeners to them.
  53. * Each property in the object response is an array of listener functions.
  54. *
  55. * @param {String|RegExp} evt Name of the event to return the listeners from.
  56. * @return {Function[]|Object} All listener functions for the event.
  57. */
  58. proto.getListeners = function getListeners(evt) {
  59. var events = this._getEvents();
  60. var response;
  61. var key;
  62. // Return a concatenated array of all matching events if
  63. // the selector is a regular expression.
  64. if (evt instanceof RegExp) {
  65. response = {};
  66. for (key in events) {
  67. if (events.hasOwnProperty(key) && evt.test(key)) {
  68. response[key] = events[key];
  69. }
  70. }
  71. }
  72. else {
  73. response = events[evt] || (events[evt] = []);
  74. }
  75. return response;
  76. };
  77. /**
  78. * Takes a list of listener objects and flattens it into a list of listener functions.
  79. *
  80. * @param {Object[]} listeners Raw listener objects.
  81. * @return {Function[]} Just the listener functions.
  82. */
  83. proto.flattenListeners = function flattenListeners(listeners) {
  84. var flatListeners = [];
  85. var i;
  86. for (i = 0; i < listeners.length; i += 1) {
  87. flatListeners.push(listeners[i].listener);
  88. }
  89. return flatListeners;
  90. };
  91. /**
  92. * Fetches the requested listeners via getListeners but will always return the results inside an object. This is mainly for internal use but others may find it useful.
  93. *
  94. * @param {String|RegExp} evt Name of the event to return the listeners from.
  95. * @return {Object} All listener functions for an event in an object.
  96. */
  97. proto.getListenersAsObject = function getListenersAsObject(evt) {
  98. var listeners = this.getListeners(evt);
  99. var response;
  100. if (listeners instanceof Array) {
  101. response = {};
  102. response[evt] = listeners;
  103. }
  104. return response || listeners;
  105. };
  106. /**
  107. * Adds a listener function to the specified event.
  108. * The listener will not be added if it is a duplicate.
  109. * If the listener returns true then it will be removed after it is called.
  110. * If you pass a regular expression as the event name then the listener will be added to all events that match it.
  111. *
  112. * @param {String|RegExp} evt Name of the event to attach the listener to.
  113. * @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling.
  114. * @return {Object} Current instance of EventEmitter for chaining.
  115. */
  116. proto.addListener = function addListener(evt, listener) {
  117. var listeners = this.getListenersAsObject(evt);
  118. var listenerIsWrapped = typeof listener === 'object';
  119. var key;
  120. for (key in listeners) {
  121. if (listeners.hasOwnProperty(key) && indexOfListener(listeners[key], listener) === -1) {
  122. listeners[key].push(listenerIsWrapped ? listener : {
  123. listener: listener,
  124. once: false
  125. });
  126. }
  127. }
  128. return this;
  129. };
  130. /**
  131. * Alias of addListener
  132. */
  133. proto.on = alias('addListener');
  134. /**
  135. * Semi-alias of addListener. It will add a listener that will be
  136. * automatically removed after its first execution.
  137. *
  138. * @param {String|RegExp} evt Name of the event to attach the listener to.
  139. * @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling.
  140. * @return {Object} Current instance of EventEmitter for chaining.
  141. */
  142. proto.addOnceListener = function addOnceListener(evt, listener) {
  143. return this.addListener(evt, {
  144. listener: listener,
  145. once: true
  146. });
  147. };
  148. /**
  149. * Alias of addOnceListener.
  150. */
  151. proto.once = alias('addOnceListener');
  152. /**
  153. * Defines an event name. This is required if you want to use a regex to add a listener to multiple events at once. If you don't do this then how do you expect it to know what event to add to? Should it just add to every possible match for a regex? No. That is scary and bad.
  154. * You need to tell it what event names should be matched by a regex.
  155. *
  156. * @param {String} evt Name of the event to create.
  157. * @return {Object} Current instance of EventEmitter for chaining.
  158. */
  159. proto.defineEvent = function defineEvent(evt) {
  160. this.getListeners(evt);
  161. return this;
  162. };
  163. /**
  164. * Uses defineEvent to define multiple events.
  165. *
  166. * @param {String[]} evts An array of event names to define.
  167. * @return {Object} Current instance of EventEmitter for chaining.
  168. */
  169. proto.defineEvents = function defineEvents(evts) {
  170. for (var i = 0; i < evts.length; i += 1) {
  171. this.defineEvent(evts[i]);
  172. }
  173. return this;
  174. };
  175. /**
  176. * Removes a listener function from the specified event.
  177. * When passed a regular expression as the event name, it will remove the listener from all events that match it.
  178. *
  179. * @param {String|RegExp} evt Name of the event to remove the listener from.
  180. * @param {Function} listener Method to remove from the event.
  181. * @return {Object} Current instance of EventEmitter for chaining.
  182. */
  183. proto.removeListener = function removeListener(evt, listener) {
  184. var listeners = this.getListenersAsObject(evt);
  185. var index;
  186. var key;
  187. for (key in listeners) {
  188. if (listeners.hasOwnProperty(key)) {
  189. index = indexOfListener(listeners[key], listener);
  190. if (index !== -1) {
  191. listeners[key].splice(index, 1);
  192. }
  193. }
  194. }
  195. return this;
  196. };
  197. /**
  198. * Alias of removeListener
  199. */
  200. proto.off = alias('removeListener');
  201. /**
  202. * Adds listeners in bulk using the manipulateListeners method.
  203. * If you pass an object as the second argument you can add to multiple events at once. The object should contain key value pairs of events and listeners or listener arrays. You can also pass it an event name and an array of listeners to be added.
  204. * You can also pass it a regular expression to add the array of listeners to all events that match it.
  205. * Yeah, this function does quite a bit. That's probably a bad thing.
  206. *
  207. * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add to multiple events at once.
  208. * @param {Function[]} [listeners] An optional array of listener functions to add.
  209. * @return {Object} Current instance of EventEmitter for chaining.
  210. */
  211. proto.addListeners = function addListeners(evt, listeners) {
  212. // Pass through to manipulateListeners
  213. return this.manipulateListeners(false, evt, listeners);
  214. };
  215. /**
  216. * Removes listeners in bulk using the manipulateListeners method.
  217. * If you pass an object as the second argument you can remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays.
  218. * You can also pass it an event name and an array of listeners to be removed.
  219. * You can also pass it a regular expression to remove the listeners from all events that match it.
  220. *
  221. * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to remove from multiple events at once.
  222. * @param {Function[]} [listeners] An optional array of listener functions to remove.
  223. * @return {Object} Current instance of EventEmitter for chaining.
  224. */
  225. proto.removeListeners = function removeListeners(evt, listeners) {
  226. // Pass through to manipulateListeners
  227. return this.manipulateListeners(true, evt, listeners);
  228. };
  229. /**
  230. * Edits listeners in bulk. The addListeners and removeListeners methods both use this to do their job. You should really use those instead, this is a little lower level.
  231. * The first argument will determine if the listeners are removed (true) or added (false).
  232. * If you pass an object as the second argument you can add/remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays.
  233. * You can also pass it an event name and an array of listeners to be added/removed.
  234. * You can also pass it a regular expression to manipulate the listeners of all events that match it.
  235. *
  236. * @param {Boolean} remove True if you want to remove listeners, false if you want to add.
  237. * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add/remove from multiple events at once.
  238. * @param {Function[]} [listeners] An optional array of listener functions to add/remove.
  239. * @return {Object} Current instance of EventEmitter for chaining.
  240. */
  241. proto.manipulateListeners = function manipulateListeners(remove, evt, listeners) {
  242. var i;
  243. var value;
  244. var single = remove ? this.removeListener : this.addListener;
  245. var multiple = remove ? this.removeListeners : this.addListeners;
  246. // If evt is an object then pass each of its properties to this method
  247. if (typeof evt === 'object' && !(evt instanceof RegExp)) {
  248. for (i in evt) {
  249. if (evt.hasOwnProperty(i) && (value = evt[i])) {
  250. // Pass the single listener straight through to the singular method
  251. if (typeof value === 'function') {
  252. single.call(this, i, value);
  253. }
  254. else {
  255. // Otherwise pass back to the multiple function
  256. multiple.call(this, i, value);
  257. }
  258. }
  259. }
  260. }
  261. else {
  262. // So evt must be a string
  263. // And listeners must be an array of listeners
  264. // Loop over it and pass each one to the multiple method
  265. i = listeners.length;
  266. while (i--) {
  267. single.call(this, evt, listeners[i]);
  268. }
  269. }
  270. return this;
  271. };
  272. /**
  273. * Removes all listeners from a specified event.
  274. * If you do not specify an event then all listeners will be removed.
  275. * That means every event will be emptied.
  276. * You can also pass a regex to remove all events that match it.
  277. *
  278. * @param {String|RegExp} [evt] Optional name of the event to remove all listeners for. Will remove from every event if not passed.
  279. * @return {Object} Current instance of EventEmitter for chaining.
  280. */
  281. proto.removeEvent = function removeEvent(evt) {
  282. var type = typeof evt;
  283. var events = this._getEvents();
  284. var key;
  285. // Remove different things depending on the state of evt
  286. if (type === 'string') {
  287. // Remove all listeners for the specified event
  288. delete events[evt];
  289. }
  290. else if (evt instanceof RegExp) {
  291. // Remove all events matching the regex.
  292. for (key in events) {
  293. if (events.hasOwnProperty(key) && evt.test(key)) {
  294. delete events[key];
  295. }
  296. }
  297. }
  298. else {
  299. // Remove all listeners in all events
  300. delete this._events;
  301. }
  302. return this;
  303. };
  304. /**
  305. * Alias of removeEvent.
  306. *
  307. * Added to mirror the node API.
  308. */
  309. proto.removeAllListeners = alias('removeEvent');
  310. /**
  311. * Emits an event of your choice.
  312. * When emitted, every listener attached to that event will be executed.
  313. * If you pass the optional argument array then those arguments will be passed to every listener upon execution.
  314. * Because it uses `apply`, your array of arguments will be passed as if you wrote them out separately.
  315. * So they will not arrive within the array on the other side, they will be separate.
  316. * You can also pass a regular expression to emit to all events that match it.
  317. *
  318. * @param {String|RegExp} evt Name of the event to emit and execute listeners for.
  319. * @param {Array} [args] Optional array of arguments to be passed to each listener.
  320. * @return {Object} Current instance of EventEmitter for chaining.
  321. */
  322. proto.emitEvent = function emitEvent(evt, args) {
  323. var listenersMap = this.getListenersAsObject(evt);
  324. var listeners;
  325. var listener;
  326. var i;
  327. var key;
  328. var response;
  329. for (key in listenersMap) {
  330. if (listenersMap.hasOwnProperty(key)) {
  331. listeners = listenersMap[key].slice(0);
  332. i = listeners.length;
  333. while (i--) {
  334. // If the listener returns true then it shall be removed from the event
  335. // The function is executed either with a basic call or an apply if there is an args array
  336. listener = listeners[i];
  337. if (listener.once === true) {
  338. this.removeListener(evt, listener.listener);
  339. }
  340. response = listener.listener.apply(this, args || []);
  341. if (response === this._getOnceReturnValue()) {
  342. this.removeListener(evt, listener.listener);
  343. }
  344. }
  345. }
  346. }
  347. return this;
  348. };
  349. /**
  350. * Alias of emitEvent
  351. */
  352. proto.trigger = alias('emitEvent');
  353. /**
  354. * Subtly different from emitEvent in that it will pass its arguments on to the listeners, as opposed to taking a single array of arguments to pass on.
  355. * As with emitEvent, you can pass a regex in place of the event name to emit to all events that match it.
  356. *
  357. * @param {String|RegExp} evt Name of the event to emit and execute listeners for.
  358. * @param {...*} Optional additional arguments to be passed to each listener.
  359. * @return {Object} Current instance of EventEmitter for chaining.
  360. */
  361. proto.emit = function emit(evt) {
  362. var args = Array.prototype.slice.call(arguments, 1);
  363. return this.emitEvent(evt, args);
  364. };
  365. /**
  366. * Sets the current value to check against when executing listeners. If a
  367. * listeners return value matches the one set here then it will be removed
  368. * after execution. This value defaults to true.
  369. *
  370. * @param {*} value The new value to check for when executing listeners.
  371. * @return {Object} Current instance of EventEmitter for chaining.
  372. */
  373. proto.setOnceReturnValue = function setOnceReturnValue(value) {
  374. this._onceReturnValue = value;
  375. return this;
  376. };
  377. /**
  378. * Fetches the current value to check against when executing listeners. If
  379. * the listeners return value matches this one then it should be removed
  380. * automatically. It will return true by default.
  381. *
  382. * @return {*|Boolean} The current value to check for or the default, true.
  383. * @api private
  384. */
  385. proto._getOnceReturnValue = function _getOnceReturnValue() {
  386. if (this.hasOwnProperty('_onceReturnValue')) {
  387. return this._onceReturnValue;
  388. }
  389. else {
  390. return true;
  391. }
  392. };
  393. /**
  394. * Fetches the events object and creates one if required.
  395. *
  396. * @return {Object} The events storage object.
  397. * @api private
  398. */
  399. proto._getEvents = function _getEvents() {
  400. return this._events || (this._events = {});
  401. };
  402. /**
  403. * Reverts the global {@link EventEmitter} to its previous value and returns a reference to this version.
  404. *
  405. * @return {Function} Non conflicting EventEmitter class.
  406. */
  407. EventEmitter.noConflict = function noConflict() {
  408. exports.EventEmitter = originalGlobalValue;
  409. return EventEmitter;
  410. };
  411. // Expose the class either via AMD, CommonJS or the global object
  412. if (typeof define === 'function' && define.amd) {
  413. define(function () {
  414. return EventEmitter;
  415. });
  416. }
  417. else if (typeof module === 'object' && module.exports){
  418. module.exports = EventEmitter;
  419. }
  420. else {
  421. exports.EventEmitter = EventEmitter;
  422. }
  423. }.call(this));