openapi-explorer
Version:
OpenAPI Explorer - API viewer with dynamically generated components, documentation, and interaction console
36 lines (34 loc) • 1.7 kB
JavaScript
;
exports.__esModule = true;
exports.reactEventListener = reactEventListener;
/**
* reactEventListener - takes the hard work out of adding and removing listeners in React
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener}
*
* @param {object} React - The React object that contains the method { useEffect }.
* @param {string} eventName - A case-sensitive string or strings representing the event type to listen for
* @param {function} callbackFunction - callback function - The object that receives a notification (an object that implements the Event interface) when an event of the specified type occurs
*/
function reactEventListener({
useEffect
}, eventName, functionCallback) {
const targetElement = window;
useEffect(() => {
targetElement.addEventListener(eventName, functionCallback);
// This is an effect that requires cleanup when the component using this
// custom hook unmounts:
// https://reactjs.org/docs/hooks-effect.html#effects-with-cleanup
return () => {
// Check if the event functionCallback we were given was a debounced or throttled
// event functionCallback, if it is, cancel any future events
// https://github.com/niksy/throttle-debounce#cancelling
if (functionCallback !== null && functionCallback !== void 0 && functionCallback.cancel) {
functionCallback.cancel();
}
// Remove the event functionCallbacks
if (targetElement !== null && targetElement !== void 0 && targetElement.removeEventListener) {
targetElement.removeEventListener(eventName, functionCallback);
}
};
}, [eventName, functionCallback, targetElement]);
}