Events
Functions for working with events: adding, removing, replacing handlers, and managing them.
Method List
Event Handler Registration and Management
| Function | Signature | Description |
|---|---|---|
on | <T extends Event>(element: HTMLElement | Document | Window, eventName: string, handler: EventHandler<T>, options?: AddEventListenerOptions | boolean): void | Registers an event handler on an element with automatic tracking for subsequent removal. |
off | (element: HTMLElement | Document | Window, eventName: string, options?: AddEventListenerOptions | boolean): void | Removes an event handler from an element. |
rebind | <T extends Event>(element: HTMLElement | Document | Window, eventName: string, handler: EventHandler<T>, options?: AddEventListenerOptions | boolean): void | Replaces an existing event handler with a new one (removes the old one, adds the new one). |
Usage Examples
Event Handler Registration
1. on
typescript
import { on, queryList } from 'snappykit';
const [button] = queryList<HTMLButtonElement>('button')!;
// Basic handler registration
on(button, 'click', (event) => {
console.log('Button clicked!', event);
});
// Registration with an event identifier
on(button, 'click.submitBtn', (event) => {
console.log('Submit button clicked!', event);
});
// Registration with options
on(button, 'click', (event) => {
console.log('Button clicked once!', event);
}, { once: true });Event Handler Removal
2. off
typescript
import { on, off, queryList } from 'snappykit';
const [button] = queryList<HTMLButtonElement>('button')!;
// Remove handler by identifier
on(button, 'click.submitBtn', () => console.log('Button clicked!'));
off(button, 'click.submitBtn'); // Removes only the handler with the identifier "submitBtn"
// Remove all handlers for an event type
off(button, 'click'); // Removes all handlers for the "click" event on the buttonEvent Handler Replacement
3. rebind
typescript
import { on, rebind, queryList } from 'snappykit';
const [button] = queryList<HTMLButtonElement>('button')!;
// Replace handler
on(button, 'click', () => console.log('Old handler'));
rebind(button, 'click', () => console.log('New handler')); // Replaces the old handler with the new one
// Replace handler with an identifier
on(button, 'click.submitBtn', () => console.log('Old handler for submitBtn'));
rebind(button, 'click.submitBtn', () => console.log('New handler for submitBtn'));Types
The following types are used in the functions above:
typescript
type EventHandler<T extends Event = Event> = (event: T) => void;