element-call-Github/src/useEvents.ts

53 lines
1.3 KiB
TypeScript
Raw Normal View History

/*
Copyright 2022-2024 New Vector Ltd.
SPDX-License-Identifier: AGPL-3.0-only
Please see LICENSE in the repository root for full details.
*/
import { useEffect } from "react";
import type {
Listener,
ListenerMap,
TypedEventEmitter,
} from "matrix-js-sdk/src/models/typed-event-emitter";
// Shortcut for registering a listener on an EventTarget
export function useEventTarget<T extends Event>(
2022-11-29 05:15:47 +08:00
target: EventTarget | null | undefined,
eventType: string,
listener: (event: T) => void,
2023-10-11 22:42:04 +08:00
options?: AddEventListenerOptions,
): void {
useEffect(() => {
if (target) {
target.addEventListener(eventType, listener as EventListener, options);
2024-06-04 23:20:25 +08:00
return (): void =>
target.removeEventListener(
eventType,
listener as EventListener,
2023-10-11 22:42:04 +08:00
options,
);
}
}, [target, eventType, listener, options]);
}
// Shortcut for registering a listener on a TypedEventEmitter
export function useTypedEventEmitter<
Events extends string,
Arguments extends ListenerMap<Events>,
2023-10-11 22:42:04 +08:00
T extends Events,
>(
emitter: TypedEventEmitter<Events, Arguments>,
eventType: T,
2023-10-11 22:42:04 +08:00
listener: Listener<Events, Arguments, T>,
): void {
useEffect(() => {
emitter.on(eventType, listener);
2024-06-04 23:20:25 +08:00
return (): void => {
emitter.off(eventType, listener);
};
}, [emitter, eventType, listener]);
}