Typescript event listeners
Created By: chatGPT
In TypeScript, handling event listeners is similar to plain JavaScript, but with the added benefits of type safety. Using event listeners allows you to execute functions in response to specific events occurring on elements in the DOM.
// Select a button element
const button = document.querySelector('button');
// Define a function to handle the event
function handleClick(event: MouseEvent): void {
console.log('Button was clicked!', event);
}
// Add event listener to the button with type safety
if (button) {
button.addEventListener('click', handleClick);
}
You can also use different types of events like
mouseover
, keydown
, and more. It is important to ensure that your event listeners are cleaned up properly, especially in applications that involve dynamic elements or use frameworks like React or Angular.// Remove event listener when necessary
function cleanup(): void {
if (button) {
button.removeEventListener('click', handleClick);
}
}
To further enhance your event handling, you might want to use Event Delegation. Instead of attaching event listeners to individual elements, you can attach a single listener to a parent element. This is especially useful when dealing with lists or dynamically generated elements.
// Parent element
const parent = document.querySelector('.parent');
// Event delegation handler
function handleEvent(event: Event): void {
const target = event.target as HTMLElement;
if (target.matches('button')) {
console.log('Button inside parent was clicked!', target);
}
}
// Attach event listener to the parent
if (parent) {
parent.addEventListener('click', handleEvent);
}