问题
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);
}
}
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>
When these select boxes are checked they continuously fire onChange()
but I do not see any executions from the debounce
function.
All of the examples I found on the web implement a debounce function that is bind to a button press or something like that.
回答1:
You can add a debounce directly to your onChange()
method and call the newly created debounced method directly in your template:
component.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>
来源:https://stackoverflow.com/questions/46613398/debounce-function-does-not-work-when-directly-not-bound-to-a-button