问题描述
我正在尝试使用Ben Alman的 debounce
。我有以下代码,但我看不到任何执行。
I am trying to use Ben Alman's debounce
code. I have the following code but I don't see anything executing at all.
onChange() {
var this_ = this
if (this.autoRefreshOn) {
Cowboy.debounce(function(e) {
console.log("debounce worked");
this_.doSomethingFunction();
}, 250);
}
}
此 onChange()
函数从 multiselect
框中触发,如下所示:
This onChange()
function is fired from multiselect
boxes like this:
<ss-multiselect-dropdown (ngModelChange)="onChange($event)"></ss-multiselect-dropdown>
<ss-multiselect-dropdown (ngModelChange)="onChange($event)"></ss-multiselect-dropdown>
<ss-multiselect-dropdown (ngModelChange)="onChange($event)"></ss-multiselect-dropdown>
<ss-multiselect-dropdown (ngModelChange)="onChange($event)"></ss-multiselect-dropdown>
选中这些选择框后,他们会持续点击 onChange()
但我没有看到 debounce
函数的执行情况。
When these select boxes are checked they continuously fire onChange()
but I do not see any executions from the debounce
function.
我找到的所有例子在网络上实现一个绑定按钮按钮或类似的debounce功能。
All of the examples I found on the web implement a debounce function that is bind to a button press or something like that.
推荐答案
你可以直接添加debounce到您的 onChange()
方法并直接在模板中调用新创建的去抖动方法:
You can add a debounce directly to your onChange()
method and call the newly created debounced method directly in your template:
组件.ts
limitedOnChange = this.debounce(this.onChange, 250);
onChange(event) { console.log('change detected: ', event) }
debounce(fn, delay) {
let timer = null;
return function () {
const context = this, args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(context, args);
}, delay);
};
}
component.html
<ss-multiselect-dropdown (ngModelChange)="limitedOnChange($event)"></ss-multiselect-dropdown>
这篇关于当直接未绑定到按钮时,去抖功能不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!