I'm currently working on a TypeScript project and am in the process of defining a function to attach event handlers to multiple events efficiently.
Instead of seeking guidance on whether my approach is ideal, I am more interested in learning how to implement it effectively. My concept involves creating a simple function that accepts the event types, the event receiver, and the callback function as parameters.
Here's an example of what I have in mind:
const addListeners = (events, htmlElement, handler) = { ... };
addListeners(['click', 'touchstart'], btn, eventType => {
console.log(`Handling ${eventType} event`);
});
In this setup, I aim to provide the event type back to the handler so that it can execute different actions based on the specific event type it encounters.
The challenge I face is determining how to restrict TypeScript to only allow the values specified in the first argument of the addListeners
function for the parameter received by the handler.
This is my current approach:
const addListeners = <E extends keyof HTMLElementEventMap, Events extends Array<E>>(events: Events, htmlElement: HTMLElement, handler: (event: string) => void): void => {
events.forEach(e => {
htmlElement.addEventListener(e, () => {
handler(e, htmlElement);
});
});
};
My focus lies on refining the (event: string) => void
aspect (the last parameter). While I believe there should be a solution, it eludes me at the moment.