durandal-2.0durandal-navigation

Deactivate composed viewmodel


There is a lot of questions about this but I cannot find any answer that works with the latest durandal version (2.1.0).

I am showing a child viewmodel inside my page using this:

<div data-bind="compose: { model: activeScreen, activationData: {id:selectedId}}"></div>

activeScreen is an observable to which I pass an string like this: viewmodels/child

It works, and the child viewmodel gets activated and shown on the screen. But when I change activeScreen, I need the child viewmodel to run deactivate. Is it possible? How?


Solution

  • So long as your child views are instance modules and not singleton modules, you can move that code to the detached handler. That's what we do as well: All of our child views are managed through dynamic composition, not child routing (which just doesn't work for the enterprise-style app). The deactivate handler comes into play in the context of routing.

    By dynamic composition I'm referring to the swapping in and out of child views/viewModels through an observable.

    But, again, the key to making this work is that the child views must be instance modules. That way they'll actually get unloaded from memory. If you go with singletons, the modules will never get detached (although there are ways to force this to happen).