javascript - angular2函数去抖的问题

查看:96
本文介绍了javascript - 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不是很好。。。希望各位多多指教

解决方案

staffSearch(event) {
    this.globalFuncService.debounceTime.apply(this, [() => this.emitSubmitDate(event), 500]);
}

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

传event则通过一个闭包实现


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

这篇关于javascript - angular2函数去抖的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆