All files / packages/core/src eventTarget.ts

100% Statements 27/27
100% Branches 10/10
100% Functions 6/6
100% Lines 27/27

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      1x     2x 1x 1x     71x       970x 584x       970x 85x     885x       1638x 770x     868x 868x   868x 676x 667x   667x           1570x   1150x     420x 420x   420x 466x     420x 1x           1x      
/**
 * EventTarget - Provides the [EventTarget](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget) interface
 */
class CornerstoneEventTarget implements EventTarget {
  private listeners;
 
  constructor() {
    this.listeners = {};
  }
 
  public reset() {
    this.listeners = {};
  }
 
  public addEventListener(type, callback) {
    if (!this.listeners[type]) {
      this.listeners[type] = [];
    }
 
    // prevent multiple callbacks from firing
    if (this.listeners[type].indexOf(callback) !== -1) {
      return;
    }
 
    this.listeners[type].push(callback);
  }
 
  public removeEventListener(type, callback) {
    if (!this.listeners[type]) {
      return;
    }
 
    const stack = this.listeners[type];
    const stackLength = stack.length;
 
    for (let i = 0; i < stackLength; i++) {
      if (stack[i] === callback) {
        stack.splice(i, 1);
 
        return;
      }
    }
  }
 
  dispatchEvent(event) {
    if (!this.listeners[event.type]) {
      //console.warn(`Skipping dispatch since there are no listeners for ${event.type}`);
      return;
    }
 
    const stack = this.listeners[event.type].slice();
    const stackLength = stack.length;
 
    for (let i = 0; i < stackLength; i++) {
      stack[i].call(this, event);
    }
 
    return !event.defaultPrevented;
  }
}
 
/**
 * EventTarget - Provides the [EventTarget](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget) interface
 */
const eventTarget = new CornerstoneEventTarget();
 
export default eventTarget;