Last active
July 20, 2017 20:25
-
-
Save EvAlex/dc3af368c0e28a8a3eb9cb00a10b267d to your computer and use it in GitHub Desktop.
EventDebounvcer for Angular
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 { Renderer2, NgZone } from '@angular/core'; | |
import { Subject } from 'rxjs/Subject'; | |
export class EventDebouncer { | |
constructor(private _zone: NgZone, private _renderer: Renderer2) { | |
} | |
listen( | |
target: 'window' | 'document' | 'body' | any, | |
eventName: string, | |
listener: (event: any) => boolean | void, | |
debounceTime: number = 40 | |
): () => void { | |
return this._zone.runOutsideAngular(() => { | |
const tempSubj = new Subject<Event>(); | |
const result = this._renderer.listen(target, eventName, (e: MouseEvent) => { | |
tempSubj.next(e); | |
e.preventDefault(); | |
e.stopPropagation(); | |
}); | |
tempSubj.debounceTime(debounceTime).subscribe(e => this._zone.run(() => listener(e))); | |
return result; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment