1

I'm using Durandal with Typescript.

My Viewmodel constructor is being called for every visit to that route. This seems like a waste. Shouldn't the state in the viewmodel be kept between different activations and then only the activate() on that instance will be called when the viewmodel is needed again?

Also, the viewmodel is still alive and running in memory after deactivation because I have some computedObservables that run code even though the user have left the viewmodel.

How do I avoid multiple constructions on the viewmodel - OR - how do I properly dispose the viewmodel after deactivation?

Anders
  • 1,216
  • 5
  • 14
  • 28

2 Answers2

0

If you export a class, Durandal defaults to constructing a new one on each new activation. This is on purpose, as it allows you to "start fresh" on each view of page. (This makes sense if you think of the RESTful model and that navigating to a new URL should usually give a "fresh" state...)

You could solve the "hanging" computed issue by disposing your computeds in a deactivate() function in your class. (Durandal lifecycle events) You could also use the new pureComputed from Knockout 3.2.

If you would still prefer to use a singleton viewmodel, you can export a singleton in your TypeScript file:

// Move this to a new file to simplify TS export restriction problems
export class MyVm { ... }

// In the module that durandal imports for its viewmodel
import myvmmodule = require('myvmmodule');
var vm = new myvmmodule.MyVm();
export = vm;
WorldMaker
  • 129
  • 6
0

If you wanted to keep the class in the same file you can also setup an interface instead to handle the TS export restrictions

// create interface in a new file
export interface IMyVM {...}

// Keep all this code in one file
import i = require('iMyVMModule');
class MyVm: i.IMyVM { ... }
var vm = new myvmmodule.MyVm();
export = vm;
Frank
  • 2,178
  • 2
  • 17
  • 24