|
| 1 | +import mitt from 'mitt' |
| 2 | +import { onBeforeUnmount } from 'vue' |
| 3 | + |
| 4 | +type EventCallback = (...args: any[]) => void |
| 5 | + |
| 6 | +interface Option { |
| 7 | + name: string |
| 8 | + callback: EventCallback |
| 9 | +} |
| 10 | + |
| 11 | +const emitter = mitt() |
| 12 | + |
| 13 | +// Map to store debounce information |
| 14 | +const lazyDebounceMap = new Map< |
| 15 | + string, |
| 16 | + { |
| 17 | + timer: any | null |
| 18 | + isPending: boolean |
| 19 | + } |
| 20 | +>() |
| 21 | + |
| 22 | +/** |
| 23 | + * Basic event emitter hook |
| 24 | + * @param option - Optional configuration with event name and callback |
| 25 | + * @returns Object containing the emitter instance |
| 26 | + */ |
| 27 | +export const useEmitt = (option?: Option) => { |
| 28 | + if (option) { |
| 29 | + emitter.on(option.name, option.callback) |
| 30 | + |
| 31 | + onBeforeUnmount(() => { |
| 32 | + emitter.off(option.name, option.callback) |
| 33 | + }) |
| 34 | + } |
| 35 | + return { |
| 36 | + emitter, |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +/** |
| 41 | + * Debounced event emitter |
| 42 | + * @param eventName - Name of the event to emit |
| 43 | + * @param params - Parameters to pass with the event |
| 44 | + * @param delay - Debounce delay in milliseconds (default: 300ms) |
| 45 | + */ |
| 46 | +export const useEmittLazy = (eventName: string, params: any = null, delay = 500) => { |
| 47 | + // If there's already a pending execution, skip this call |
| 48 | + if (lazyDebounceMap.has(eventName)) { |
| 49 | + const entry = lazyDebounceMap.get(eventName)! |
| 50 | + if (entry.isPending) { |
| 51 | + return |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + // Clear existing timer if present |
| 56 | + if (lazyDebounceMap.has(eventName)) { |
| 57 | + const { timer } = lazyDebounceMap.get(eventName)! |
| 58 | + if (timer) { |
| 59 | + clearTimeout(timer) |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + // Set up a new timer |
| 64 | + const timer = setTimeout(() => { |
| 65 | + emitter.emit(eventName, params) |
| 66 | + |
| 67 | + // Mark execution as complete |
| 68 | + if (lazyDebounceMap.has(eventName)) { |
| 69 | + lazyDebounceMap.get(eventName)!.isPending = false |
| 70 | + } |
| 71 | + }, delay) |
| 72 | + |
| 73 | + // Store timer information and mark as pending |
| 74 | + lazyDebounceMap.set(eventName, { |
| 75 | + timer, |
| 76 | + isPending: true, |
| 77 | + }) |
| 78 | + |
| 79 | + // Clean up on component unmount |
| 80 | + onBeforeUnmount(() => { |
| 81 | + if (lazyDebounceMap.has(eventName)) { |
| 82 | + const { timer } = lazyDebounceMap.get(eventName)! |
| 83 | + if (timer) { |
| 84 | + clearTimeout(timer) |
| 85 | + } |
| 86 | + lazyDebounceMap.delete(eventName) |
| 87 | + } |
| 88 | + }) |
| 89 | +} |
0 commit comments