javascript - Javascript Debounce 没有从 vue 组件中清除它的队列
问题描述
我正在使用这里的去抖方法https://www.freecodecamp.org/news/javascript-debounce-example/
function debounce(func, timeout = 300){
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => { func.apply(this, args); }, timeout);
};
}
function saveInput(){
console.log('Saving data');
}
const processChange = debounce(() => saveInput());
我想包含在我们拥有的图书馆中,所以common.js
我有:
export default {
otherStuff,
debounce(func, timeout = 300) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, args);
}, timeout);
};
},
在 vue.js 我有一个文本框有一个事件@keyup="searchboxChange()"
在方法部分:
import common from "@/assets/js/Service/Common";
... stuff removed for brevity
methods:
{
searchboxChange(){
common.debounce(() => this.filterChanged(), 1000)();
},
}
我必须在 debounce 方法的末尾包含 () 否则它实际上并没有触发。然而,虽然它完美地去抖动,但当超时到期时,每个事件都会被触发。this.filterChanged()
因此,如果我的搜索是“HELLO”,我会看到 5 个请求在被调用 5 次的同时被触发。
我确信超时变量的范围很简单,因为在 debounce 方法中添加一个 console.log 表明每次都未定义计时器。
解决方案
您需要对组件方法进行去抖,否则您将从组件方法中调用多个去抖函数。
像这样的东西应该工作
methods: {
// ...
searchboxChange: common.debounce(function() {
this.filterChanged();
}, 1000)
}
注意与function
短函数语法相对的使用。您需要这样做以确保正确的词法范围this
推荐阅读
- cil - 有没有办法检查代码中的 CIL 评估堆栈?
- java - AndroidX 迁移 AndroidTestCase 后,AndroidJUnit4 & InstrumentationRegistry.getTargetContext 被弃用
- csvhelper - 使用 CsvHelper.CsvWriter 忽略日期格式的午夜
- loops - SAS——按组处理保留第一个和最后一个点
- php - 从 woocommerce 的订单详细信息页面中提取产品 URL 的功能
- algorithm - 90 角与行进立方体算法 - 插值功能
- mapbox-android - 运行/调试 mapbox android 代码示例的问题
- php - 如何每 20 分钟运行一次我的 PHP 脚本
- javascript - 如何使用 Knex 重新排序列?
- java - 如何从文本字段设置文本(在标签中)