Cataclysm
Cataclysm

Reputation: 8598

Does detach() method call after attach() method?

I have a simple UI class

public class HelloWorldUI extends UI {

@Override
protected void init(VaadinRequest request) {
    System.out.println("Initialized !");
    final VerticalLayout layout = new VerticalLayout();
    layout.addComponent(new Label("Hello World !"));
    setContent(layout);
}

@Override
public void detach() {
    System.out.println("Detach !");
    super.detach();
}

@Override
public void attach() {
    System.out.println("Attach !");
    super.attach();
}
}

When first time my UI was loaded , I see outputs at my console as

Attach !
Initialized !

It is OK and this is what I expected. But when I refresh the browser , my console outputs were

Attach !
Initialized !
Detach !

Amazing ! I think Detach ! may be produce first because (as I think) when browser was refreshed , detach() method should be call and attach() , init() should be follow . But actually detach() method will call after attach() method. What's wrong my thinking ?

Upvotes: 1

Views: 1504

Answers (1)

Henri Kerola
Henri Kerola

Reputation: 4967

Browser Refresh = New UI Instance

When you refresh a browser window or tab, a new UI instance is created. So you see an attach message of a new UI instance. The old UI instance will be detached later.

This is default behavior in Vaadin 7. You may change that behavior with an annotation.

@PreserveOnRefresh

Adding @PreserveOnRefresh annotation to the UI changes the behavior: No new UI instance won't be created on refresh.

To quote the doc for this annotation:

Marks a UI that should be retained when the user refreshed the browser window. By default, a new UI instance is created when refreshing, causing any UI state not captured in the URL or the URI fragment to get discarded. By adding this annotation to a UI class, the framework will instead reuse the current UI instance when a reload is detected.

Upvotes: 6

Related Questions