Constructor called, Attach called

Can you explain the life cycle in vaadin 10?

I have a project with some views: IndexView, CompanyView etc.
According to https://vaadin.com/docs/v10/flow/routing/tutorial-routing-lifecycle.html there exists a attach method. Is the constructor everytime called when the view is opened (I call a component with @route annotation a view)? If this is not the case one should stick to the attach method?

@Route()
@Viewport("width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes")
public class MainView extends VerticalLayout {
  public MainView() {
  }

  @Override
  protected void onAttach(AttachEvent attachEvent) {
  }

Which controller are you talking about?

Hi Olli,

I added an example code and corrected the error “controller” instead of “constructor”. I do not understand why a onAttach is needed when the constructor is called everytime. I usually put everything in the constructor.

Hi,

The onAttach method’s role is such that it’s called each time when a Component is attached to a parent on the client side. The same Object could be attached and detached several times, but it’s always only constructed once. This difference might be useful in certain situations.

Using the onAttach method has some benefits in Flow: you can be certain that the Component is in fact a part of a UI (so for example, you know that getUI() returns an object) and it’s ok to do things that have a direct effect on the client-side (for example, you can execute some JavaScript only after the component has been attached). In the constructor, doing these things might not result in the behavior you want.

Regarding navigation, you should also take a look at the docs on the Navigation Lifecycle events chapter: https://vaadin.com/docs/v11/flow/routing/tutorial-routing-lifecycle.html - typically, you should put navigation-related code in the relevant navigation event handler.

-Olli