ComponentAttach and Detach Events

Hi,

I’m trying to get informed about attach and detach events for arbitrary components. I looked at the api and the corresponding junit ComponentAttachDetachListenerTest but noticed that the listeners will be triggered for the container ( or even a layout of a container ) and not the individual component…

Any way to get a callback for this kind of event? In Swing this was simply done via a HierarchyListener…something like

    public void startupController(JComponent component , final Controller controller) {
        if (controller.getActivationMode() == ActivationMode.ON_SHOW) {
            component.addAncestorListener(new AncestorListener() {
                public void ancestorAdded(AncestorEvent event) {
                    activateController(controller);
                }

                public void ancestorRemoved(AncestorEvent event) {
                    deactivateController(controller);
                }

                public void ancestorMoved(AncestorEvent event) {
                }
            });
        else   if (controller.getActivationMode() == ActivationMode.ON_ADD) {
            component.addHierarchyListener( new HierarchyListener() {
                public void hierarchyChanged(HierarchyEvent event) {
                    if ((event.getChangeFlags() & HierarchyEvent.PARENT_CHANGED) != 0) {
                        if (component.getParent() != null)
                            activateController(controller);
                        else
                            deactivateController(controller);
                    }
                }
            });
        } // else 

Thanx

Hi,

Currently, there is no simple way to do this in core Vaadin.

In my project, I have created some iterators that - given an arbitrary component - will walk the tree of components beneath it.
Oh - I’ve just remembered, I put this code on BitBucket
here
. Feel free to use and abuse as you like; FWIW, I’m not planning to maintain the project (I just pulled the stuff out of my closed source project).

If you wanted to have certain components notified on attach/detach, I’d implement a marker interface, implement ComponentAttachListener on the root component, and do something like this :


   Iterable<? extends Component> componentTree = ComponentIterables.componentTreeBreadthFirst(this);

    for (Component component : componentTree) {
      if (component instanceof YourMarker) {
        ((YourMarker) thing).componentAdded();        
      }
    }

You could also have a self propogating ComponentAttach/COmponentDetach listener, which adds/removes itself from all ComponentContainer’s : just add it once at the Window/Root level, and you can be notified as any object gets added or removed from the component tree.

In short, it’s possible - but you need to do a bit of work yourself.

HTH,

Cheers,

Charles