我在Wicket中有两个面板。ParentPanel
和ChildPanel
情境ChildPanel
是ParentPanel
的组件。
每次在“父面板”中触发某个事件时,我都想在ChildPanel
中添加某个javascript。
工作方案ParentPanel.java
public class ParentPanel extends Panel
{
private static final long serialVersionUID = 4306746527837380863L;
private final ChildPanel childPanel;
public ParentPanel(String aId, IModel<AnnotatorState> aModel)
{
super(aId);
model = aModel;
// initially the Child panel is empty. passing empty model
childPanel = new ChildPanel("child-container", Model.of());
childPanel.setOutputMarkupId(true);
add(childPanel);
}
@OnEvent
public void onClickText(RenderEvent aEvent)
{
LOG.trace("Event Fired");
IPartialPageRequestHandler iPartialPageRequestHandler = aEvent.getRequestHandler();
Integer someData = getSomeData();
childPanel.setDefaultModel(Model.of(someData));
//I am trying to add the child panel to the ajax target to ensure rerendering of child panel.
iPartialPageRequestHandler.add(childPanel);
}
}
ChildPanel.java
public class ChildPanel extends Panel
{
private static final long serialVersionUID = -3849226240909011148L;
private static final Logger LOG = LoggerFactory.getLogger(ChildPanel.class);
private IModel<Integer> model;
public ChildPanel(String aId, IModel<Integer> aModel)
{
super(aId);
model = (aModel);
}
@Override
public void renderHead(IHeaderResponse aResponse)
{
super.renderHead(aResponse);
model = (IModel<Integer>) getDefaultModel();
if (model == null)
return;
Integer someData = model.getObject();
String someJavascript = createSomeJavascript(someData);
log.debug("Rendering Updated UI with the JS: ", javascript);
aResponse.render(OnDomReadyHeaderItem.forScript(javascript));
}
}
显然,每次将childPanel添加到iPartialPageRequestHandler时,都会调用renderHead(),它的工作是在
ParentPanel
中触发的每个事件上更新UI。问题
但是,有人告诉我这不是一个好习惯。由于在这种情况下,JS被添加到renderHead()中,因此它最终出现在页面源代码中-当发送(大)JSON数据时,它变得很麻烦。仅在Wicket可能/可行的情况下,才需要找到一个将JS附加到AJAX目标的好地方(也许render()或onRender()或onAfterRender()可能更好)。由于我的知识有限,我无法猜测我还能如何实现该方案。任何其他(更好或更可行的)解决方案都值得欢迎和赞赏。
谢谢。
最佳答案
我认为问题是createSomeJavascript
创建了很多代码?
然后,我将对其进行重构,以使createSomeJavascript
仅调用使用JavaScriptResourceReference
添加到组件的函数。这样,只有一小部分Javascript最终出现在源代码中。
例如,将您的javascript放在这样的外部文件中:
private static final ResourceReference JS_QM = new JavaScriptResourceReference( ClientPanel.class, "question.mark.js" );
@Override
public void renderHead( Component component, IHeaderResponse response )
{
super.renderHead( component, response );
response.render( JavaScriptReferenceHeaderItem.forReference( JS_QM, "question-mark" ) );
...
}