All files / packages/core/src/utilities triggerEvent.ts

85.71% Statements 6/7
62.5% Branches 5/8
100% Functions 1/1
80% Lines 4/5

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                                                    3066x 3066x       3066x         3066x    
import eventTarget from '../eventTarget';
 
/**
 * Small utility to trigger a custom event for a given EventTarget.
 *
 * @example
 *
 * ```javascript
 * triggerEvent(element, Events.IMAGE_RENDERED, { element })
 * ```
 * or it can trigger event on the eventTarget itself
 *
 * ```javascript
 * triggerEvent(eventTarget, CSTOOLS_EVENTS.ANNOTATION_MODIFIED, { viewportId, annotationUID })
 * ```
 *
 * @param el - The element or EventTarget to trigger the event upon
 * @param type - The event type name
 * @param detail - The event detail to be sent
 * @returns false if event is cancelable and at least one of the event handlers
 * which received event called Event.preventDefault(). Otherwise it returns true.
 */
export default function triggerEvent(
  el: EventTarget = eventTarget,
  type: string,
  detail: unknown = null
): boolean {
  Iif (!type) {
    throw new Error('Event type was not defined');
  }
 
  const event = new CustomEvent(type, {
    detail,
    cancelable: true,
  });
 
  return el.dispatchEvent(event);
}