svelte-slim
Version:
A lightweight event management library for Svelte.
70 lines (65 loc) • 2.4 kB
JavaScript
// src/core/logger.ts
const DEBUG = typeof process !== 'undefined' && process.env.DEBUG === 'true';
function log(...args) {
if (DEBUG) {
console.log('[slim]', ...args);
}
}
class EventBus {
constructor() {
this.listeners = new Map();
}
on(event, config) {
var _a, _b;
const handlers = (_a = this.listeners.get(event)) !== null && _a !== void 0 ? _a : [];
const handler = config.handler;
handler.stopPropagation = (_b = config.stopPropagation) !== null && _b !== void 0 ? _b : false;
handlers.push(handler);
this.listeners.set(event, handlers);
log(`Registered handler for event "${event}". Total handlers: ${handlers.length}`);
}
off(event, handlerToRemove) {
const handlers = this.listeners.get(event);
if (!handlers) {
log(`No handlers found for event "${event}" when trying to remove.`);
return;
}
const filtered = handlers.filter((h) => h !== handlerToRemove);
this.listeners.set(event, filtered);
log(`Removed handler from event "${event}". Remaining handlers: ${filtered.length}`);
}
async emit(event, ...args) {
const handlers = this.listeners.get(event);
if (!handlers) {
log(`Emit called for event "${event}" but no handlers registered.`);
return;
}
log(`Emitting event "${event}" to ${handlers.length} handler(s) with args:`, args);
for (const handler of handlers) {
try {
await handler(...args);
log(`Handler for event "${event}" completed.`);
if (handler.stopPropagation) {
log(`Event "${event}" propagation stopped by handler.`);
break;
}
}
catch (error) {
console.error(`[slim] Error in handler for event "${event}":`, error);
}
}
}
}
const bus = new EventBus();
function useEvents(events) {
const entries = Object.entries(events);
entries.forEach(([event, config]) => bus.on(event, config));
return () => {
entries.forEach(([event, config]) => bus.off(event, config.handler));
};
}
async function dispatch(event, ...args) {
await bus.emit(event, ...args);
}
export { dispatch, useEvents };
//# sourceMappingURL=index.esm.js.map