Skip to content

Commit

Permalink
feat(signal): add debounce feature
Browse files Browse the repository at this point in the history
  • Loading branch information
MM25Zamanian committed Jun 11, 2024
1 parent 80055d6 commit 6a50158
Show file tree
Hide file tree
Showing 4 changed files with 10 additions and 4 deletions.
3 changes: 2 additions & 1 deletion packages/signal/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
},
"dependencies": {
"@gecut/logger": "workspace:^",
"@gecut/types": "workspace:^"
"@gecut/types": "workspace:^",
"@gecut/utilities": "workspace:^"
}
}
5 changes: 4 additions & 1 deletion packages/signal/src/libraries/_signal.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {GecutLogger} from '@gecut/logger';
import debounce from '@gecut/utilities/debounce.js';

import type {SubscribeOptions, Subscriber} from '../type.js';

Expand All @@ -20,6 +21,7 @@ export abstract class Signal<T> {
protected value: T | undefined;
protected hasDispatched = false;
protected log: GecutLogger;
protected debounceConfig: false | 'AnimationFrame' | 'IdleCallback' | number = false;

/**
* Unsubscribes a previously registered callback from the signal.
Expand Down Expand Up @@ -67,9 +69,10 @@ export abstract class Signal<T> {
this.hasDispatched = true;
this.value = newValue;

setTimeout(() => this.__$dispatch(newValue), 0);
this.__$debouncedDispatch(newValue);
}

protected __$debouncedDispatch = debounce(this.__$dispatch, this.debounceConfig !== false ? this.debounceConfig : 0);
protected __$dispatch(newValue: T): void {
for (const subscriber of this.subscribers) {
if (subscriber && !subscriber.options.disabled) {
Expand Down
4 changes: 3 additions & 1 deletion packages/signal/src/libraries/context.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import {Signal} from './_signal.js';

export class ContextSignal<T> extends Signal<T> {
constructor(name: string) {
constructor(name: string, debounce: false | 'AnimationFrame' | 'IdleCallback' | number = false) {
super(name, 'context');

this.debounceConfig = debounce;
}

/**
Expand Down
2 changes: 1 addition & 1 deletion packages/signal/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@

"include": ["src/**/*.ts"],
"exclude": [],
"references": [{"path": "../logger"}, {"path": "../types"}]
"references": [{"path": "../logger"}, {"path": "../types"}, {"path": "../utilities"}]
}

0 comments on commit 6a50158

Please sign in to comment.