EventHelper.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import defined from "./defined.js";
  2. import DeveloperError from "./DeveloperError.js";
  3. /**
  4. * A convenience object that simplifies the common pattern of attaching event listeners
  5. * to several events, then removing all those listeners at once later, for example, in
  6. * a destroy method.
  7. *
  8. * @alias EventHelper
  9. * @constructor
  10. *
  11. *
  12. * @example
  13. * const helper = new Cesium.EventHelper();
  14. *
  15. * helper.add(someObject.event, listener1, this);
  16. * helper.add(otherObject.event, listener2, this);
  17. *
  18. * // later...
  19. * helper.removeAll();
  20. *
  21. * @see Event
  22. */
  23. function EventHelper() {
  24. this._removalFunctions = [];
  25. }
  26. /**
  27. * Adds a listener to an event, and records the registration to be cleaned up later.
  28. *
  29. * @param {Event} event The event to attach to.
  30. * @param {Function} listener The function to be executed when the event is raised.
  31. * @param {object} [scope] An optional object scope to serve as the <code>this</code>
  32. * pointer in which the listener function will execute.
  33. * @returns {EventHelper.RemoveCallback} A function that will remove this event listener when invoked.
  34. *
  35. * @see Event#addEventListener
  36. */
  37. EventHelper.prototype.add = function (event, listener, scope) {
  38. //>>includeStart('debug', pragmas.debug);
  39. if (!defined(event)) {
  40. throw new DeveloperError("event is required");
  41. }
  42. //>>includeEnd('debug');
  43. const removalFunction = event.addEventListener(listener, scope);
  44. this._removalFunctions.push(removalFunction);
  45. const that = this;
  46. return function () {
  47. removalFunction();
  48. const removalFunctions = that._removalFunctions;
  49. removalFunctions.splice(removalFunctions.indexOf(removalFunction), 1);
  50. };
  51. };
  52. /**
  53. * Unregisters all previously added listeners.
  54. *
  55. * @see Event#removeEventListener
  56. */
  57. EventHelper.prototype.removeAll = function () {
  58. const removalFunctions = this._removalFunctions;
  59. for (let i = 0, len = removalFunctions.length; i < len; ++i) {
  60. removalFunctions[i]();
  61. }
  62. removalFunctions.length = 0;
  63. };
  64. /**
  65. * A function that removes a listener.
  66. * @callback EventHelper.RemoveCallback
  67. */
  68. export default EventHelper;