angular2函数去抖的问题

在angular2环境中写了一个自定义的debounce函数,因为使用了服务中的本地变量,所以没有使用闭包
在传入函数作为参数时,遇到了两个问题

  1. 如何给传入函数加入参数

  2. 如何将传入函数的作用域绑定在声明他的component中


代码如下

debounceTime(fn, delay) {
if (isUndefined(this.timeout)) {
this.timeout = setTimeout(() => {
            fn();
        }, delay);
    } else {
        clearTimeout(this.timeout);
        this.timeout = setTimeout(() => {
            fn();
        }, delay);
    }
}
 emitSubmitDate(event) {
    this.submit_data['search'] = event.value;
    this.globalFuncService.setInfoListSource(this.request_type, this.request_url,               
           this.submit_data);
    this.globalFuncService.emitInfoListSource();
}
staffSearch(event) {
    this.globalFuncService.debounceTime(this.emitSubmitDate, 500);
}
希望将event作为参数传入emitSubmit函数,然后再将带有event的emitSubmit传入debounce
实际遇到的问题是this的变化导致各种undefined

本人js不是很好。。。希望各位多多指教
阅读 2.7k
2 个回答
staffSearch(event) {
    this.globalFuncService.debounceTime.apply(this, [() => this.emitSubmitDate(event), 500]);
}

apply变更this指向,也可以用call或bind

传event则通过一个闭包实现


PS: angular2本身就依赖了Rx,何必自己写debounceTime....

你可以试试es6的箭头函数,函数内的this就是你定义时的this

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题