IDetachListener saves the day

i just asked this on the Wicket user list:

we have a problem here, which we think might be a common one, so i´d like to discuss.

from time to time we create models (mostly LDMs) that are not actually reachable by components. (yes, you can argue that this is stupid, but it happens where 1:1 mapping between component and model is not easy to apply)

the problem arising from there is of course that wicket does not know about this IModel and so wont detach() it.

yes, we could use Component.detach() as a hook to detach that LDM as well, but i tend to forget that.

and i´d like to share what came out of it. The important lines are:

 Java |  copy |? 
public class ReflectiveDetachListener implements IDetachListener
{
    public void onDetach(final Component component)
    {
        final Class< ?> clazz = component.getClass();
        Set< Field > fields = this.fieldMap.get(clazz);
        if (fields == null)
        {
            fields = findFields(clazz);
            this.fieldMap.put(clazz, fields);
        }
 
        for (final Field field : fields)
        {
            if (isToBeDetached(field.getType()))
            {
                final IDetachable d = (IDetachable) getFieldValue(component, field.getName());
                if (d != null)
                {
                    d.detach();
                }
            }
        }
    }
 
    private boolean isToBeDetached(final Class< ?> type)
    {
        return IDetachable.class.isAssignableFrom(type) && (!Component.class.isAssignableFrom(type));
    }
    // ....
}

You get the picture… if you need more info or source, i´ll be happy to send it over.

4 comments to IDetachListener saves the day

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>