我有一个从 FormBuilder 构建的控件。 我想为每个按键设置一个 debounceTime,但不是在用户失去控件焦点时设置。
this._control.valueChanges
.pipe(
takeUntil(this.ngUnsubscribe),
debounceTime(1000),
distinctUntilChanged()
)
.subscribe((value) => {
// Logic goes here
});
-------------------------------
onInputChange(event: any): void {
console.log(this.autoComplete.focus, "1"); // Return true
setTimeout(() => console.log(this.autoComplete.focus, "2")); // return false
}
所以第一个控制台日志是 true,而带有 setTimeout 的控制台日志是 false
将 keyup 的去抖时间设置为 1000 是有意义的,因此它可以防止对后端服务的多次调用,但在发生丢失焦点事件的情况下这没有意义。
我可能在这里遗漏了一些东西,但是
如何在同一控件上为不同的事件实现不同的 debounceTime ?
最佳答案
理想情况下,您需要区分lostFocus 和输入键盘。
这是您修改后的示例:
merge(
this._control.valueChanges.pipe(
filter(() => this.autoComplete.focus === true),
debounceTime(1000),
distinctUntilChanged(),
),
this._control.valueChanges.pipe(
filter(() => this.autoComplete.focus === false),
distinctUntilChanged(),
),
)
.pipe(takeUntil(this.ngUnsubscribe))
.subscribe((value) => {
// Logic goes here
});
这样你就合并了 this._control.valueChanges
的两个版本,一个负责 keyup,另一个负责 focuslost
关于javascript - 如何在同一控件上为不同事件实现不同的 debounceTime?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57058163/