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?
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.
One big difference I see here is that activate method has a Promis as return value so you can run here async code. Triggering async code in constructor is a very bad idea. Further detail is that constructor must not throw an exception so typically here you just assign constructor parameters to local variables without any logic. I would not do more stuff in constructor and the actual viewmodel initialization with logic should happen in activate or attached method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With