Component Lifecycle Callbacks

Sometimes the content of a component depends on resources that are not available during the construction of the component. You can postpone the content creation until the component is attached to the UI by overriding the onAttach() method from Component.

Java

  1. @Tag("div")
  2. public class UserNameLabel extends Component {
  3. @Override
  4. protected void onAttach(AttachEvent attachEvent) {
  5. // user name can be stored to session after login
  6. String userName = (String) attachEvent.getSession().getAttribute("username");
  7. getElement().setText("Hello " + userName + ", welcome back!");
  8. }
  9. }

The onAttach method is invoked by the framework when the Component has been attached to the UI. Its counterpart, the onDetach method is invoked right before the component is detached from the UI. They are good places to reserve and release any resources used by the component.

Java

  1. @Tag("div")
  2. public class ShoppingCartSummaryLabel extends Component {
  3. private final Consumer<EventObject> eventHandler = this::onCartSummaryUpdate;
  4. @Override
  5. protected void onAttach(AttachEvent attachEvent) {
  6. ShopEventBus eventBus = attachEvent.getSession().getAttribute(ShopEventBus.class);
  7. // registering to event bus for updates from other components
  8. eventBus.register(eventHandler);
  9. }
  10. @Override
  11. protected void onDetach(DetachEvent detachEvent) {
  12. ShopEventBus eventBus = detachEvent.getSession().getAttribute(ShopEventBus.class);
  13. // after detaching don't need any updates
  14. eventBus.unregister(eventHandler);
  15. }
  16. private void onCartSummaryUpdate(EventObject event) {
  17. // update cart summary ...
  18. }
  19. }
  20. interface ShopEventBus {
  21. void register(Consumer<EventObject> eventHandler);
  22. void unregister(Consumer<EventObject> eventHandler);
  23. }
Note
The getUI() in Component returns an Optional<UI> because a component is not always attached. Using the attach or detach event to get the UI or the session is a more convenient way as they are always available.
Note
The default implementations of the onAttach and onDetach methods in the Component class are empty, so you don’t need to call super.onAttach() or super.onDetach() from your overridden methods. However, when extending other component implementations, you might need to do that.
Tip
If you are interested in knowing when another component gets attached or detached, you can use the Component.addAttachListener and Component.addDetachListener. The corresponding events are fired after the onAttach and onDetach methods are invoked. The getUI() method for the component will return the UI instance during both events.