Daniel Billingham Daniel Billingham - 9 days ago 9
Javascript Question

Aurelia class Constructor vs Activate

When exporting an es6 class, which is acting as a view model in aurelia, I seem to be able to set initialization code in both the constructor and an activate function.

Are there any standard conventions here?

Should I be doing certain initialization in one but not the other?

Is the activate function there for users not implementing es6 classes?

Answer

You can set instance properties in both constructor and activate methods, they are both going to be invoked by Aurelia. However, there is sort of conceptual difference here.

Activate is one of the screen activation lifecycle methods and should ideally be used to control screen/view-model behavior only. For example, canDeactivate method controls whether view-model can be navigated to, etc. Activate is also a hook which is executed just before view-model gets rendered (but before attached hook). However, it is possible that activate method will never be called is say route navigates away in constructor or canActivate methods rejects/returns false - in this case construct will still be invoked, but activate will be not.

On the other hand, construct method is invoked before any other hooks and methods, so it's called before activate. For this reason, construct is a primary place for setting configuration properties because it is takes dependency injections. So while activate takes fixed set of parameters (params, routeConfig, navigationInstruction), parameters list passed to constructor method depends on what services you inject into your view-model class.

Comments