Reputation: 4185
I thought when using dependency injection in Aurelia, you would get singletons by default. That doesn't seem to be the case with custom elements.
Say I have 3 custom elements named a
, b
and c
. a
and b
are siblings are the same page. c
is an element inside of b
's template. I'm injecting c
into a
.
When I do this, I get a new instance of c
in a
. Is there a way to make c
a singleton?
Here is a plunker example: http://plnkr.co/edit/Au80u0?p=preview
Upvotes: 2
Views: 549
Reputation: 6622
Custom elements cannot be singletons because they can be used multiple times, it would not really make sense architecturally that an element could or would act as a singleton.
Imagine referencing the same element 3 times on a page, they would all have the same state if they were singletons and not expected custom element behaviour. However, you can create a shared service class which you inject (and is a singleton).
What I did in an Aurelia project of mine is create a class called MyCustomElementMediator (replace MyCustomElement with the name of your element). This allows you to handle state for a component. This does not make sense for multiple occurrences of a custom element, but if you are only using it in one place, then this approach works.
Upvotes: 4