Event Handling
Handle timepicker events using EventEmitter API or callbacks
EventEmitter API (Recommended)
#The new EventEmitter API provides a clean, type-safe way to handle events:
index.js
const picker = new TimepickerUI(input);picker.create();picker.on('confirm', (data) => {console.log('Time confirmed:', data.hour, data.minutes);});picker.on('cancel', (data) => {console.log('Cancelled');});picker.on('open', () => {console.log('Picker opened');});picker.on('update', (data) => {console.log('Time updated:', data);});picker.on('select:hour', (data) => {console.log('Hour selected:', data.hour);});picker.on('select:minute', (data) => {console.log('Minute selected:', data.minutes);});picker.on('select:period', (data) => {console.log('Period selected:', data.type);});picker.once('confirm', (data) => {console.log('This runs only once');});const handler = (data) => console.log(data);picker.on('confirm', handler);picker.off('confirm', handler);
Callback Options
#You can also use callback options (check console):
Range Change Log
#range:change fires when the user changes the time of a range end. It carries the end that changed and both ends after the change. Open the picker and pick a time to fill the log. setRange() and the other API calls do not emit it. New in 4.7.0.
Legacy DOM Events (Removed in v4.0.0)
#DOM events have been removed in v4.0.0. Use EventEmitter API or callback options instead:
index.js
// REMOVED in v4.0.0 - No longer supportedinput.addEventListener('timepicker:confirm', (e) => {console.log(e.detail);});// CORRECT - use the EventEmitter APIpicker.on('confirm', (data) => {console.log(data);});// CORRECT - or use callback optionsconst picker = new TimepickerUI(input, {callbacks: {onConfirm: (data) => {console.log(data);}}});
TypeScript Event Types
#Payload types are exported from timepicker-ui, and on() infers them from the event name:
index.ts
import { TimepickerUI } from 'timepicker-ui';import type { ConfirmEventData, ErrorEventData } from 'timepicker-ui';// ConfirmEventData:// {// hour?: string;// minutes?: string;// seconds?: string; // only with clock.showSeconds// type?: string; // 'AM' or 'PM' in 12h mode// autoCommit?: boolean; // true when wheel.commitOnScroll confirmed it// }const picker = new TimepickerUI(input);picker.create();// data is typed from the event namepicker.on('confirm', (data) => {console.log(data.hour, data.minutes, data.type);});// or name the payload type yourselfconst handleError = (data: ErrorEventData) => {console.error(data.error);};picker.on('error', handleError);const handleConfirm = (data: ConfirmEventData) => {console.log(data.hour, data.minutes);};picker.on('confirm', handleConfirm);