19

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?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Daniel Billingham
  • 1,391
  • 5
  • 15
  • 25

2 Answers2

20

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.

dfsq
  • 191,768
  • 25
  • 236
  • 258
  • 1
    I can't find any documentation on Aurelia's site that speaks to 'activate()' or 'canActivate()'. Where is this information? – lux Dec 16 '15 at 14:22
  • 3
    Aurelia documentation is still pretty bad.. But you can find some info here: https://github.com/aurelia/documentation/blob/master/English/docs.md#the-screen-activation-lifecycle – dfsq Dec 16 '15 at 14:36
  • @ImanouPetit https://github.com/aurelia/framework/blob/master/doc/article/en-US/cheat-sheet.md#the-route-screen-activation-lifecycle – GFoley83 Nov 26 '16 at 00:40
  • Example here: https://plnkr.co/edit/Johtku?p=preview taken from https://www.danyow.net/es7-async-await-with-aurelia/ – GFoley83 Nov 26 '16 at 00:41
8

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.

Lukas K
  • 6,037
  • 4
  • 23
  • 31