Last active
April 25, 2019 12:52
-
-
Save alexsanqp/07a5e5ba456ea2f0f7a3a66ff6f4fc50 to your computer and use it in GitHub Desktop.
Triggers an event listener outside the angular zone.
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 { Inject, Injectable, NgZone } from '@angular/core'; | |
import { EVENT_MANAGER_PLUGINS, EventManager } from '@angular/platform-browser'; | |
export const RUN_OUTSIDE: string = '.run-outside'; | |
/** | |
* @example | |
* | |
* @NgModule({ | |
* // ... | |
* providers: [ | |
* { | |
* provide: EventManager, | |
* useClass: RunOutsideEventManagerService, | |
* }, | |
* ], | |
* // ... | |
* }) | |
* export class AppModule {} | |
* | |
* // ... | |
* import { RUN_OUTSIDE } from '__PATH_TO__/run-outside-event-manager.service'; | |
* | |
* @HostListener(`document:mousemove{RUN_OUTSIDE}`, ['$event']) | |
* public onMouseMoveOutsideAngular(event: MouseEvent): void { | |
* // ... | |
* this.cdRef.detectChanges(); | |
* } | |
*/ | |
@Injectable() | |
export class RunOutsideEventManagerService extends EventManager { | |
public constructor( | |
@Inject(EVENT_MANAGER_PLUGINS) plugins: any[], | |
public zone: NgZone, | |
) { | |
super(plugins, zone); | |
} | |
/** | |
* @inheritDoc | |
*/ | |
public addEventListener(element: HTMLElement, eventName: string, handler: Function): Function { | |
if (this.isOutside(eventName)) { | |
const clearEventName: string = eventName.split('.')[0]; | |
return this.zone.runOutsideAngular<Function>(() => { | |
return super.addEventListener(element, clearEventName, handler); | |
}); | |
} | |
return super.addEventListener(element, eventName, handler); | |
} | |
/** | |
* @inheritDoc | |
*/ | |
public addGlobalEventListener(target: string, eventName: string, handler: Function): Function { | |
if (this.isOutside(eventName)) { | |
const clearEventName: string = eventName.split('.')[0]; | |
return this.zone.runOutsideAngular<Function>(() => { | |
return super.addGlobalEventListener(target, clearEventName, handler); | |
}); | |
} | |
return super.addGlobalEventListener(target, eventName, handler); | |
} | |
/** | |
* @param {string} name | |
* @return {boolean} | |
*/ | |
private isOutside(name: string): boolean { | |
const regOut: RegExp = new RegExp(`${RUN_OUTSIDE}$`); | |
return regOut.test(name); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment