简体   繁体   中英

view-models are singletons? or not?

The Aurelia docs on the use of Containers is clear that "Each time the Router navigates to a screen, it creates a child container to encapsulate all the resources related to that navigation event and then auto-registers the screen's view-model in that child container. As you know, auto-registration, by default, results in the view-model being registered as a singleton."

However, what I see in my application is that all view-model constructors are by default being being invoked whenever the associated view is activated. This is not view-model "singleton" behavior as I understand it.

Can anyone explain what I'm not understanding here?

Thanks

It's important to understand the effect of child containers on lifetime. When the router navigates, it creates a child container and it registers the screen's view model within that child container. It is a singleton, scoped to that child container, not at the application level. So, when that child container gets disposed (next time there is a navigation), all the singletons registered within it also get disposed.

If you want the view-model to "outlive" the navigation request cycle, you can use the @singleton() decorator.

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