javawicketwicket-6wicket-1.5

Wicket - Set Model from another panel


I am quite new to Wicket. I am adding a model to a sub-panel(ChartPanel) from a main panel (MainPanel) on a button click.

MainPanel.java

On button click, I am re-adding the chartPanel after I change its model. Following is the code I am using in the buttonClick of the MainPanel. Here the onRenderAnnotations event is generated on some click in the UI.

 @OnEvent
public void onRenderAnnotations(RenderAnnotationsEvent aEvent)
{
    LOG.trace("clicked on the annotation");

    renderChart( aEvent.getRequestHandler());
}

private void renderChart(IPartialPageRequestHandler aRequestHandler)
{
    MultiValuedMap<String, Double> recommenderScoreMap = getLatestScores(aRequestHandler);
    Map<String,String> curveData = new HashMap<String,String>();
    LearningCurve learningCurve = new LearningCurve();

    for (String recommenderName : recommenderScoreMap.keySet()) {
        String data = recommenderScoreMap.get(recommenderName).stream().map(Object::toString)
                .collect(Collectors.joining(", "));

        curveData.put(recommenderName,data);

        learningCurve.setCurveData(curveData);

        learningCurve.setMaximumPointsToPlot(MAX_POINTS_TO_PLOT);
    }
    chartPanel.setDefaultModel(Model.of(learningCurve));

    // to avoid the error, A partial update of the page is being rendered
    try {
        aRequestHandler.add(chartPanel);
    }
    catch (IllegalStateException e) {
        LOG.warn("Not updating the chart. " + e.toString());
        setResponsePage(getPage());
    }
}

ChartPanel.java

After this in the chartPanel, I want to use the updated model to add component inside the chartpanel. What would be the best way to do that?

I want to do something like this in the class ChartPanel:

@Override
protected void onRender()
{
    super.onModelChanged();

    LearningCurve newLearningCurve = getModel().getObject();

    requestTarget = ???

    String js = createJavascript(newLearningCurve);
    requestTarget.prependJavascript(js);
}

My question is, in the above code how to get the request target since it is not an ajax request neither do I get it in the arguments. Should I use some other function where I also get a requestTarget. But I want it to be called every time the model of ChartPanel is updated from anywhere.

Pardon my ignorance. I have been trying for a few days but I am still stuck. I tried to explain it enough but if any information is missing, please comment and I will add it right away.

Thanks.


Solution

  • You should override renderHead() instead:

    @Override
    public void renderHead(IHeaderResponse response)
    {
        super.renderHead(response);
    
        response.render(OnLoadHeaderItem.forScript(
                createJavascript(newLearningCurve)));
    }
    

    This way your chart will be shown correctly regardless whether it was added due to an AjaxRequest or simply when the page is rerendered.