magicmn
magicmn

Reputation: 1914

Pass model to child component

Let's say I have the following setup.

public class TextPanel extends Panel {

    public TextPanel(String id) {
        this(id, null);
    }

    public TextPanel(String id, IModel<?> model) {
        super(id, model);
        add(new Label("text", model));
    }
}

What is the best way to keep the model of the label up-to date. There are two ways I can think of but I am not sure if there are any draw backs or better ways.

Overriding onModelChanged and call get("text").setDefaultModel(getDefaultModel()) or implementing a (new?) model.

public class DefaultComponentModel implements IModel<Object> {

    private final Component component;

    public DefaultComponentModel(Component component) {
        this.component = component;
    }

    @Override
    public Object getObject() {
        return component.getDefaultModelObject();
    }

    public void setObject(Object object) {
        component.setDefaultModelObject(object);
    }
}

And use it for the label. (new Label("text", new DefaultComponentModel(this)))

Important is that the solution should work when the defaultModel of a component changes or a CompoundPropertyModel is used.

Upvotes: 2

Views: 113

Answers (1)

martin-g
martin-g

Reputation: 17533

I'd replace this(id, null); with this(id, Model.of(""));. This way you can update the TextPanel's model object (e.g. textPanel.setModelObject("new text")) and this will automatically update the Label.

If you set a new model (i.e. textPanel.setModel(newModel) then you will have to override TextPanel#setModel() method and call get("text").setModel(newModel) too.

Upvotes: 2

Related Questions