UNPKG

@ou-imdt/utils

Version:

Utility library for interactive media development

56 lines (47 loc) 1.54 kB
import { name } from '../Base.js'; // defines a getter that returns a prefix for (custom) events, defaults to [name] export const eventPrefix = Symbol('eventPrefix'); // defines a getter to return default custom event options export const eventOptions = Symbol('eventOptions'); // defines a getter to return a default custom event detail object export const eventDetail = Symbol('eventDetail'); export default (superClass) => class DispatchEventMixin extends superClass { constructor() { super(); } get [eventPrefix]() { return `${this[name]}-`; } get [eventOptions]() { return { bubbles: true, composed: true, // propagate across shadow DOM boundary into light DOM }; } // will likely need to return instance props get [eventDetail]() { return null; } dispatchEvent(type, { target, detail, ...options } = {}) { const event = ((value) => { if (value instanceof Event) return value; const prefixedType = `${this[eventPrefix]}${type}`; const mergedOptions = { ...this[eventOptions], ...options, detail: { ...this[eventDetail], ...detail } }; return new CustomEvent(prefixedType, mergedOptions); })(type); if (target instanceof EventTarget) { target.dispatchEvent(event); } else { if (typeof super.dispatchEvent !== 'function') return; // super instanceof errors super.dispatchEvent(event); } // console.log(`dispatch custom event: ${event.type}`, event); } }