Fixed debounce decorator
This commit is contained in:
parent
7ec9b548fa
commit
276b202f6a
@ -1,14 +1,23 @@
|
||||
export function Debounce(delay = 300): MethodDecorator {
|
||||
return function _debounce(_target: unknown, propertyKey: PropertyKey, descriptor: PropertyDescriptor) {
|
||||
let timeout: number | undefined;
|
||||
import { debounce, DebouncedFunc } from 'lodash';
|
||||
|
||||
interface DebounceSettings {
|
||||
readonly leading?: boolean;
|
||||
readonly maxWait?: number;
|
||||
readonly trailing?: boolean;
|
||||
}
|
||||
|
||||
export function Debounce(milliseconds = 300, options?: DebounceSettings): MethodDecorator {
|
||||
return function _debounce(_target: unknown, _propertyKey: PropertyKey, descriptor: PropertyDescriptor) {
|
||||
const map = new WeakMap();
|
||||
const descriptorCopy = { ...descriptor };
|
||||
|
||||
descriptorCopy.value = function _new(...args: unknown[]) {
|
||||
clearTimeout(timeout);
|
||||
timeout = window.setTimeout(() => (descriptor.value as (...params: unknown[]) => unknown).apply(this, args), delay);
|
||||
descriptorCopy.value = function _value(...args: unknown[]): void {
|
||||
let debounced: DebouncedFunc<any> = map.get(this) as DebouncedFunc<any>;
|
||||
if (!debounced) {
|
||||
debounced = debounce(descriptor.value, milliseconds, options).bind(this);
|
||||
map.set(this, debounced);
|
||||
}
|
||||
debounced(...args);
|
||||
};
|
||||
|
||||
return descriptorCopy;
|
||||
};
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user