overleaf/services/web/frontend/js/features/ide-react/scope-event-emitter/react-scope-event-emitter.ts
Alf Eaton 678f0eb498 Fix React scope event listener (#16434)
GitOrigin-RevId: 1846ad511f915ff48f2f20a8b8a7f1174bb21525
2024-01-10 09:03:05 +00:00

31 lines
1,023 B
TypeScript

import {
ScopeEventEmitter,
ScopeEventName,
} from '../../../../../types/ide/scope-event-emitter'
export class ReactScopeEventEmitter implements ScopeEventEmitter {
// eslint-disable-next-line no-useless-constructor
constructor(private readonly eventEmitter: EventTarget) {}
emit(eventName: ScopeEventName, broadcast: boolean, ...detail: unknown[]) {
this.eventEmitter.dispatchEvent(new CustomEvent(eventName, { detail }))
}
on(eventName: ScopeEventName, listener: (...args: unknown[]) => void) {
// A listener attached via useScopeEventListener expects an event as the
// first parameter. We don't have one, so just provide an empty object
const wrappedListener = (event: CustomEvent<unknown[]>) => {
listener({}, ...event.detail)
}
this.eventEmitter.addEventListener(
eventName,
wrappedListener as EventListener
)
return () => {
this.eventEmitter.removeEventListener(
eventName,
wrappedListener as EventListener
)
}
}
}