Created
August 8, 2019 11:35
-
-
Save zzpmaster/16fb71c4b6cad2bb733f49666ee3af67 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@angular/core'; | |
import { EventManager } from '@angular/platform-browser'; | |
import { Subject, Subscription } from 'rxjs'; | |
import { debounceTime, throttle, throttleTime } from 'rxjs/operators'; | |
type TimeoutHandler = () => Function; | |
/** | |
* prevent debounce click | |
*/ | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class DebounceClickService { | |
public manager: EventManager; | |
public miliseconds: number = 500; | |
private eventName: string = 'click'; | |
public supports(eventName: string): boolean { | |
// return /debounce|throttle/.test(eventName); | |
return this.eventName === eventName; | |
} | |
public addEventListener(element: HTMLElement, eventName: string, ohandler: Function): Function { | |
// const innerHanlder = (event: any) => this.manager.getZone().runGuarded(() => ohandler(event)); | |
// this.clicks.pipe(debounceTime(this.miliseconds)).subscribe((_: any) => ohandler(event)); | |
// const handler = this.debounce(innerHanlder, this.miliseconds); | |
const clicks = new Subject(); | |
const subscription: Subscription = clicks.pipe(throttleTime(this.miliseconds)).subscribe((_: any) => { | |
ohandler(event); | |
}); | |
const hanlder = (): void => { | |
console.log(element); | |
clicks.next(); | |
}; | |
this.manager.getZone().runOutsideAngular(() => { | |
element.addEventListener(eventName, (e: any) => hanlder()); | |
}); | |
return () => { | |
element.removeEventListener(eventName, (e: any) => hanlder()); | |
subscription.unsubscribe(); | |
}; | |
} | |
private debounce(eventFunction: Function, delay: number): Function { | |
let out: any; | |
// tslint:disable-next-line | |
return function (): void { | |
const args: Object = arguments; | |
const later: TimeoutHandler = () => { | |
out = null; | |
return eventFunction.apply(this, args); | |
}; | |
clearTimeout(out); | |
// tslint:disable-next-line: no-string-based-set-timeout | |
out = setTimeout(later, delay); | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment