Basil Bourque
Basil Bourque

Reputation: 339372

Lifecycle of a Layout (or Component) in Vaadin?

What hooks do I have into the lifecycle of a Layout specifically, or Component generally in Vaadin 7?

Lifecycle Events?

I want to know when a Layout is starting (being born) and stopping (dying). Specifically, I suspect I really care about "attach" and "detach". The Layout could exist off screen before use on-screen and even afterwards if I might re-display that Layout later in the user’s work session. I think attachment is that process of joining/leaving the displayed UI, but I’m not sure.

Motivation: Notification, in Observer Pattern

Not that it matters, but the reason I care about the lifecycle is shown in the Push page of the Book of Vaadin 7. As seen there, I want to notify a bunch of users’ Layouts (in UIs) about a change in the data represented by their widgets. So each Layout needs to have a method invoked, to make them update their widgets with fresh data.

To notify each Layout, I need to know which Layout instances exist and are interested in this kind of update. So I keep a collection of Layouts that register themselves. Basically, the Observer pattern. That Push page shows such a registry collection.

The missing piece: Where in the Layout's code do I make the Layout instance register and unregister? I suppose I could the Java constructor and finalize method. But I suspect I really want registration to revolve around the attach and detach events.

Attach/Detach Events

The Layout doc lists many attach/detach listeners and attach/detach methods. I'm not sure which I should be using, if any.

Upvotes: 1

Views: 2275

Answers (1)

cfrick
cfrick

Reputation: 37063

your assumptions are correct. when a component gets the parent set it is attached to the UI (or in general the session). so this component is relevant for the client (yet it might not be visible right now in the client).

one way to deal with this is overriding attach() and/or detach() to fire your logic to register/deregister.

or by adding listeners for attach and detach: AttachListener for addAttachListener

    def layout = new VerticalLayout()
    layout.addAttachListener(new ClientConnector.AttachListener() {
        @Override
        void attach(ClientConnector.AttachEvent attachEvent) {
            println "Attach: $attachEvent"
        }
    })
    layout.addDetachListener(new ClientConnector.DetachListener() {
        @Override
        void detach(ClientConnector.DetachEvent detachEvent) {
            println "Detach: $detachEvent"
        }
    })

Upvotes: 3

Related Questions