去抖@HostListener 事件 [英] Debounce @HostListener event
问题描述
我正在 Angular2 中实现一个简单的无限滚动指令.我正在使用 @HostListener('window:scroll')
来获取滚动事件并解析 $target
中的数据.
I'm implementing a simple infinite-scroll directive in Angular2.
I'm using @HostListener('window:scroll')
to get the scroll event and parsing the data from the $target
.
问题是,对于每个滚动事件,一切都将在不需要的情况下再次检查.
The question is, for every scroll event, everything will be checked once again with no need.
我检查了 ionic infinite-scroll
指令以获得灵感,但他们不使用 @HostListener
,我猜他们需要更精细的控制.
I checked the ionic infinite-scroll
directive for inspiration but they don't use @HostListener
, they need a more granular control, I guess.
我在搜索 https://github.com/angular/angular/时发现了这个问题问题/13248但找不到任何方法来做我想做的事.
I ended up on this issue while searching https://github.com/angular/angular/issues/13248 but couldn't find any way to do what I want.
我认为,如果我创建一个 Observable,使用去抖动订阅它并将(下一个)项目推送到它,我将达到我想要的行为,但我无法做到这一点.
I think if I create an Observable, subscribe to it with debounce and push (next) items to it, I will reach the behaviour I want, but I'm not being able to do that.
推荐答案
我会利用 debounce 方法装饰器,例如:
I would leverage debounce method decorator like:
export function debounce(delay: number = 300): MethodDecorator {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const timeoutKey = Symbol();
const original = descriptor.value;
descriptor.value = function (...args) {
clearTimeout(this[timeoutKey]);
this[timeoutKey] = setTimeout(() => original.apply(this, args), delay);
};
return descriptor;
};
}
并按如下方式使用它:
@HostListener('window:scroll', ['$event'])
@debounce()
scroll(event) {
...
}
这篇关于去抖@HostListener 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!