Debounce function does not work when directly not bound to a button

馋奶兔 提交于 2019-12-11 10:58:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!