1

I want to create a single instance of an object with a large external API, and share it among several components of my app.

This API has several event methods (e.g. onJoin(), onClose(), onOpen(), etc.) which I need to implement. As different events are associated with different components of my app, I was thinking of implementing these events within those components, rather than all within a Singleton class.

Alternatively, I was wondering if I should--or even could--have each of these event methods trigger a custom event created with EventEmitter, and have listener methods in each of the relevant component classes ready to handle these events. But it appears that EventEmitter can only be used by components and directives, not plain classes.

Another concern is whether I should create a Singleton class for this object or treat it as a kind of 'Service' and inject it into the dependent components.

Any help is much appreciated!

Thanks

Maximilian Riegler
  • 22,720
  • 4
  • 62
  • 71
Brendan B
  • 369
  • 3
  • 19

1 Answers1

0

Instead of using EventEmitter, which after some trial and error I discovered didn't work (the event callback function were getting called late, or not at all), I implemented the callback functions within the external library. These initial functions use window.dispatchEvent(event) to emit a CustomEvent, passing into it their original 'event' parameter. This event can then be picked up inside my app using @HostListener('window:onWhatever', ['$event']).

Here is where I got this solution from.

I also used a Service to handle initializing the external library object and encapsulate its functions and options. This approach seems to be working well.

Community
  • 1
  • 1
Brendan B
  • 369
  • 3
  • 19