'Remove Event Handler using Abort Signal with Typescript and React
I am building a portal that ultimately fetches xml-like documents and displays them in the browser, and whenever I load one of these pages, I need to attach onclick and mouseover handlers to several elements on the page.
However, the user can navigate between several of these pages and I'm running into issues with multiple handlers being attached to a single element.
So, I would like to attach a handler containing an abort signal, so that whenever I change pages I can imply abort and remove all the handler at once, but I can't seem to get typescript to play along.
An example of the code:
export const attachElementModifiers = (
elementObject: { [key: string]: Element },
elementPointerClass: string,
listener: (evt: any) => void,
onHoveringHandler: (_evt: any, key: string) => void,
onMouseOutHandler: (_evt: any) => void,
controller: AbortController
): void => {
for (const [key] of Object.entries(elementObject)) {
elementObject[key].classList.add(elementPointerClass)
elementObject[key].addEventListener('click', listener)
elementObject[key].addEventListener('mouseover', (_evt: any) =>
onHoveringHandler(_evt, key)
)
elementObject[key].addEventListener(
'mouseleave',
(_evt: any) => onMouseOutHandler(_evt),
{ signal: controller.signal } // <---- ERROR HERE
)
}
}
The following error always shows up:
No overload matches this call.
Overload 1 of 2, '(type: keyof ElementEventMap, listener: (this: Element, ev: Event) => any, options?: boolean | AddEventListenerOptions | undefined): void', gave the following error.
Argument of type '"mouseleave"' is not assignable to parameter of type 'keyof ElementEventMap'.
Overload 2 of 2, '(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions | undefined): void', gave the following error.
Argument of type '{ signal: AbortSignal; }' is not assignable to parameter of type 'boolean | AddEventListenerOptions | undefined'.
Object literal may only specify known properties, and 'signal' does not exist in type 'AddEventListenerOptions'.ts(2769)
I know that AbortSignal exists in lib.dom.d.ts, however I'm not sure how to properly use it here.
Solution 1:[1]
You can fix this by
elementObject[key].addEventListener(
'mouseleave',
(_evt: any) => onMouseOutHandler(_evt),
{ signal: controller.signal } as AddEventListenerOptions
)
I'm not sure why our options object is causing that error even when it has properties that match the AddEventListenerOptions interface.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Frazer Kirkman |
