Skip to main content

dispatchEvent

import { dispatchEvent } from '@uhg-abyss/parcels/tools/dispatchEvent';

Overview

The dispatchEvent tool is used to dispatch custom events to the window, allowing for communication between web/parcel components. This tool is useful for sending data from one component to another, or for triggering events that other components are listening for. This tool is meant to be used in conjunction with the registerEventListener tool if you aren't using React. If you are using React, you should use the useRegisterEventListener hook.

This tool is bidirectional, meaning that it can be used to dispatch events in both web and parcel components.

Properties

dispatchEvent(
eventName: string,
detail?: object,
)

Usage

dispatchEvent takes in two parameters:

  1. eventName: a string representing the name of the custom event to be dispatched.
  2. detail (optional): an object containing additional data to be sent with the event. It defaults to an empty object if not provided.
() => {
const onSubmit = () => {
dispatchEvent('parcelSubmit', { message: 'Form submitted!' });
};
return (
<div>
<Button onClick={onSubmit}>Hello</Button>
</div>
);
};

Example

The example below demonstrates how to use the dispatchEvent tool in conjunction with the registerEventListener tool to send data from the parcel to the web component.

// Example parcel file
import React from 'react';
import { Button } from '@uhg-abyss/web/ui/Button';
import { dispatchEvent } from '@uhg-abyss/parcels/tools/dispatchEvent';
export const ParcelApp = () => {
// Add a dispatch event to the parcel component
const onSubmit = () => {
// When the button is clicked, the event will be dispatched
dispatchEvent('parcelSubmit', { message: 'Form submitted!' });
};
return (
<div>
<Button onClick={onSubmit}>Hello</Button>
</div>
);
};
// Example web file
import React, { useCallback, useState } from 'react';
import { useRegisterEventListener } from '@uhg-abyss/parcels/hooks/useRegisterEventListener';
import { Modal } from '@uhg-abyss/web/ui/Modal';
export const HelloAbyss = () => {
const [isOpen, setIsOpen] = useState(false);
// Memoize the handler function using useCallback
// By using useCallback, you prevent useRegisterEventListener from unnecessarily
// removing and re-adding the event listener whenever the component re-renders
const handleWebSubmit = useCallback((event) => {
setIsOpen(true);
}, []); // Dependencies array is empty since setIsOpen doesn't change
// Add a register event to the parcel component to listen for when the parcel component dispatches the event
useRegisterEventListener('parcelSubmit', handleWebSubmit);
return (
<div>
<abyss-parcel import="parcel-app@test" />
<Modal title="Register" isOpen={isOpen} onClose={() => setIsOpen(false)}>
<Modal.Section> Form submitted! </Modal.Section>
</Modal>
</div>
);
};
Table of Contents