All files / engine/Source/Core EventHelper.js

94.44% Statements 17/18
50% Branches 1/2
100% Functions 4/4
93.75% Lines 15/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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