Monitoring and Events
The Monitor Module is a high-performance toolkit for event listening and state observation.
Through a unified encapsulation, it addresses common pain points such as forgotten cleanups during component destruction and debugging difficulties associated with native addEventListener, ResizeObserver, and MutationObserver. It also features built-in capabilities for debounce, throttle, and diagnostic debugging.
Import Method
import {
tEvent,
tResize,
tMutation,
tTimer,
tInterval,
tMitt,
tMonitor
} from "@techui/utils";Event Listening
tEvent is an enhanced wrapper for native DOM events that supports automatic deduplication, debug tracking, and batch cleanup.
Basic API
- add(el, name, handler, uid, capture): Binds an event.
uid: A critical parameter. It serves as a unique ID to identify the event, preventing duplicate logic binding and allowing for precise removal later.
- remove(el, name, uid): Removes the event listener associated with a specific UID.
- removeAll(el): Removes all events bound to the element through
tEvent.
const btn = document.querySelector('#btn');
const handler = () => console.log('Click');
// Bind event with UID 'btnClick_01'
tEvent.add(btn, 'click', handler, 'btnClick_01');
// Remove event
tEvent.remove(btn, 'click', 'btnClick_01');Advanced: Debounce and Throttle
tEvent directly exposes two high-frequency optimization functions.
- debounce(fn, wait, immediate): Debounce. Ideal for search box inputs or window resizing. It executes the function only once after N milliseconds have passed since the last trigger.
- throttle(fn, wait, options): Throttle. Ideal for scroll events or mouse movements. It executes the function once every N milliseconds.
// Debounce: Execute search 500ms after the user stops typing
const onSearch = tEvent.debounce((val) => {
api.search(val);
}, 500);
// Throttle: Trigger layout calculation once every 100ms during scrolling
const onScroll = tEvent.throttle(() => {
updateLayout();
}, 100);Mutation Observation
tResize (Dimension Observation)
An encapsulation based on ResizeObserver.
- o(elements, callback, duration): Starts observation (Observe). Supports passing a single element or an array. The
durationparameter controls the throttle frequency of the callback (default is 100ms). - d(elements): Stops observation (Disconnect) and cleans up memory.
tResize.o(document.querySelector('.chart-box'), (entries) => {
console.log('Container size changed, redrawing chart');
});tMutation (DOM Mutation Observation)
An encapsulation based on MutationObserver used to monitor additions/removals of DOM nodes or attribute changes.
- o(elements, callback, options, duration): Starts observation.
optionscan be configured to listen for child nodes (childList) or attributes (attributes). - d(elements): Stops observation (Disconnect).
Timer Management
TechUI recommends using these encapsulated timers to avoid memory leaks caused by "zombie timers".
tTimer (Timeout)
- s(id, fn, ms): Sets a timeout (Set). The
idis used to overwrite any existing timer with the same name. - c(id): Clears a timeout (Clear).
- w(ms): Wait (Promise). Achieve
await sleep(1000)with a single line of code.
// Simple asynchronous wait
await tTimer.w(1000);
// Set a named timer (if a timer named 'refresh' exists, it is automatically cancelled)
tTimer.s('refresh', () => getData(), 500);tInterval (Interval)
Similar in usage to tTimer, used for managing recurring interval timers.
Debugging and Diagnostics
This is the most powerful feature of the Monitor module. When you are unsure how many timers or listeners are running on a page, you can enable global debug mode.
Enable Debugging
// Enable debug logs for all modules
tMonitor.enable();
// Or enable individually
tEvent.enableDebug();View Reports
Calling tMonitor() in the console will output a table of all currently active listeners, timers, and the class names of their bound DOM elements.
tMonitor();
// Console Output:
// 🔍 All Monitor Debug Info
// ┌─────────┬──────────────┐
// │ (index) │ Values │
// ├─────────┼──────────────┤
// │ uid_01 │ "click [btn]"│
// └─────────┴──────────────┘Event Bus
A minimalist implementation of the Pub/Sub pattern (Event Bus).
- on(type, handler): Subscribe.
- emit(type, data): Publish.
- off(type, handler): Unsubscribe.
const bus = tMitt();
bus.on('login', (user) => console.log(user));
bus.emit('login', { name: 'Ayin' });