Last active
August 31, 2020 09:13
-
-
Save ZeevKatz/cdeb555efeedeea6e72d5c5a83b10819 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** | |
* Supported events for analytics. | |
*/ | |
export type AnalyticsEvent = 'click' | 'focus' | 'blur'; | |
/** | |
* Directive that used to log client events to the analytics provider by using {@link AnalyticsService}. | |
*/ | |
@Directive({ selector: '[analytics]' }) | |
export class AnalyticsDirective implements OnChanges { | |
/** | |
* List of supported events for analytics. | |
*/ | |
@Input() | |
readonly events: AnalyticsEvent[]; | |
/** | |
* Set of properties to attach to the logged events. | |
*/ | |
@Input() | |
readonly properties: Record<string, Primitive> = {}; | |
constructor( | |
private readonly elementRef: ElementRef, | |
private readonly analyticsService: AnalyticsService | |
) {} | |
ngOnChanges({ events }: SimpleChanges) { | |
if (events) { | |
this.registerEvents(this.events) | |
.pipe(untilDestroyed(this)) | |
.subscribe(event => this.logEvent(event, this.properties)); | |
} | |
} | |
logEvent(event: Event, properties: Record<string, Primitive>) { | |
this.analyticsService.logEvent({type: event.type, ...properties}); | |
} | |
registerEvents(events: AnalyticsEvent[]): Observable<Event> { | |
const { nativeElement: element } = this.elementRef; | |
const eventsObservables = events.map(event => fromEvent<Event>(element, event)); | |
return merge(...eventsObservables); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment