events_trigger.js

import assign from '../data/object-assign';

/**
 * @module trigger
 * @description Trigger an event, either native or custom, and optionally pass data along.
 *
 * @since 1.0.0
 *
 * @param {{data: {uuid: (*|string)}, native: boolean, event: string}} opts        The options object.
 * @param {object}                                                     opts.data   Data to pass inside an object with the event.
 *                                                                                 Available as `event.detail` in the listener.
 * @param {Document|Window|HTMLElement}                                opts.el     The element to trigger the event on.
 * @param {string}                                                     opts.event  The event name.
 * @param {boolean}                                                    opts.native Whether or not the event is a native browser event or a custom one.
 *
 * @requires assign
 *
 * @return {void}
 *
 * @example
 * import { trigger } from "@gravityforms/utils";
 *
 * function Example() {
 *     trigger( { event: 'gform/flyout/open', native: false, data: {
 *         something: 'we need',
 *     } } );
 * };
 *
 * // elsewhere in the codebase
 *
 * document.addEventListener( 'gform/flyout/open', function( event ) {
 *     console.log( event.detail.something );
 * } );
 *
 */
export default function trigger( opts = {} ) {
	let event;
	const options = assign(
		{
			data: {},
			el: document,
			event: '',
			native: true,
		},
		opts
	);

	if ( options.native ) {
		event = document.createEvent( 'HTMLEvents' );
		event.initEvent( options.event, true, false );
	} else {
		try {
			event = new window.CustomEvent( options.event, {
				detail: options.data,
			} );
		} catch ( e ) {
			event = document.createEvent( 'CustomEvent' );
			event.initCustomEvent( options.event, true, true, options.data );
		}
	}

	options.el.dispatchEvent( event );
}