简体   繁体   中英

Custom Element Singletons in Aurelia

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM