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.


Hi!
We have been discussing about centrally cached models on wicket users at: http://www.nabble.com/When-NOT-to-use-models—td26025016.html
Someone suggested looking at your blog. I am left wondering how automatic this detach listener is? Does it obey the hollywood principle?
**
Martin
sure. in Application init i just apply it like :
and it is called by wicket. In onDetach you see, that it just reflectively iterates over fields to find IDetachables that are not Components itself.
Cool. How do you detach the listener itself in a controlled manner?
Why should it be detached? It does not have any state connected to the request-lifecycle. In fact, it is completely stateless.