Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
978 views
in Technique[技术] by (71.8m points)

angular - Debounce @HostListener event

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.

I checked the ionic infinite-scroll directive for inspiration but they don't use @HostListener, they need a more granular control, I guess.

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
  };
}

and use it as follows:

@HostListener('window:scroll', ['$event'])  
@debounce() 
scroll(event) {
  ...
}

Ng-run Example


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...