Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 401
Daniel Billingham Avatar asked Jul 30 '15 20:07

Daniel Billingham


2 Answers

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.

like image 112
dfsq Avatar answered Nov 16 '22 11:11

dfsq


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.

like image 8
Lukas K Avatar answered Nov 16 '22 11:11

Lukas K