You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Listenable.js 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import EventEmitter from './EventEmitter';
  2. /**
  3. * The class implements basic event operations - add/remove listener.
  4. * NOTE: The purpose of the class is to be extended in order to add
  5. * this functionality to other classes.
  6. */
  7. export default class Listenable {
  8. /**
  9. * Creates new instance.
  10. * @constructor
  11. */
  12. constructor() {
  13. this.eventEmitter = new EventEmitter();
  14. // aliases for addListener/removeListener
  15. this.addEventListener = this.on = this.addListener;
  16. this.removeEventListener = this.off = this.removeListener;
  17. }
  18. /**
  19. * Adds new cancellable listener.
  20. * @param {String} eventName the name of the event
  21. * @param {Function} listener the listener.
  22. * @returns {Function} - The unsubscribe function.
  23. */
  24. addCancellableListener(eventName, listener) {
  25. this.addListener(eventName, listener);
  26. return () => this.removeListener(eventName, listener);
  27. }
  28. /**
  29. * Adds new listener.
  30. * @param {String} eventName the name of the event
  31. * @param {Function} listener the listener.
  32. * @returns {EventEmitter} - The emitter, so that calls can be chained.
  33. */
  34. addListener(eventName, listener) {
  35. return this.eventEmitter.addListener(eventName, listener);
  36. }
  37. /**
  38. * Removes listener.
  39. * @param {String} eventName the name of the event that triggers the
  40. * listener
  41. * @param {Function} listener the listener.
  42. * @returns {EventEmitter} - The emitter, so that calls can be chained.
  43. */
  44. removeListener(eventName, listener) {
  45. return this.eventEmitter.removeListener(eventName, listener);
  46. }
  47. /**
  48. * Emits an event.
  49. * @param {string} event - event name
  50. */
  51. emit(event, ...args) {
  52. this.eventEmitter.emit(event, ...args);
  53. }
  54. }