All files / packages/core/src eventTarget.ts

100% Statements 24/24
100% Branches 10/10
100% Functions 5/5
100% Lines 24/24

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            2x 1x       66x       905x 545x       905x 79x     826x       1520x 728x     792x 792x   792x 614x 609x   609x           1474x   1045x     429x 429x   429x 438x     429x             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;