防抖@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.
我检查了离子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/时遇到了这个问题Issues/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.
推荐答案
我会使用防抖动方法装饰器,例如:
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) {
...
}
Ng-run Example
这篇关于防抖@HostListener事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!