[英]How to pass argument if event handler is assigned in initialization function?
[英]Pass an argument to function, assigned to variable
我正在尝试去抖动我的一些代码,为此我使用以下函数:
private debounce(func, wait, immediate) {
var timeout;
return function () {
var context = this, args = arguments;
var later = function () {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
然后,为了使用它,我这样做:
var showDataOnMove = this.debounce(function (evt) {
console.log('moving');
}, 500, false);
当我在这段代码中调用它时,它按预期工作:
this._map.on('pointermove', (evt) => {
showDataOnMove();
});
但是,我意识到,我不知道如何将任何参数传递给我的去抖动函数,当它附加到一个变量时(例如,我想将此 evt 传递给 showDataOnMove()),我尝试了不同的方法,比如这个:
var showDataOnMove = (evt) => this.debounce(function (evt) {
console.log('moving');
console.log(evt);
}, 500, false);
但它也没有奏效。 我怎么能把参数传递给这个函数?
最简单的方法可能是创建一个闭包。 您已经这样做了,但是您随后重新声明了捕获的变量,从而破坏了它。 这应该是这样的:
// Function in debounce has no argument
var showDataOnMove = evt => {
this.debounce(() => {
console.log('moving');
console.log(evt);
}, 500, false)(); // Call the function returned by debounce
};
您分配showDataOnMove
初始版本应该可以正常工作,这是一个更好的类型示例,其中debouce
返回与作为参数传入的函数类型相同的函数:
class DebounceExample
{
private debounce<T extends (...args: any[]) => void>(func: T, wait: number, immediate: boolean): T
{
// Depending on environment (e.g. Node or browser) this should be typed differently
var timeout: any;
return function (this: any, ...args)
{
var context = this;
var later = function ()
{
timeout = undefined;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow)
func.apply(context, args);
} as T;
};
constructor()
{
// Example usage
var showDataOnMove = this.debounce(function (evt: number) {
console.log(evt);
}, 500, false);
setTimeout(() => showDataOnMove(1));
setTimeout(() => showDataOnMove(2));
setTimeout(() => showDataOnMove(3));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.