I'm familiar with the patterns that are used to clean up subscriptions on observables as outlined here: Angular/RxJs When should I unsubscribe from Subscription
But is there a similar pattern for cleaning up event handlers?
I have a component which modifies a dynamically provided template to apply some event handlers to various elements among other things. There are other subscriptions involved and cleaned up using ngrx-take-until-destroy
simplifying everything further. Currently, I'm just maintaining a separate array of Unsubscribable
to collect and cleanup when destroyed.
@Component(...)
class MyComponent implements OnInit, OnDestroy {
constructor(private renderer: Renderer2, private service: SomeService) {}
private subscriptions: Unsubscribable[] = [];
ngOnInit() {
this.service.doSomething(...).pipe(
untilDestroyed(this)
).subscribe(...);
}
private setTagLink(
element: Element,
clickHandler: (event: any) => (boolean|void)
) {
this.subscriptions.push({
unsubscribe: this.renderer.listen(element, 'click', clickHandler)
});
}
ngOnDestroy() {
this.subscriptions.forEach(s => s.unsubscribe());
}
}
I'd rather not maintain this array and in a similar fashion have some automatic cleanup of the listeners. What are my options?