您将 AjaxEventBehavior 添加到不正确的 AjaxEditableMultiLineLabel。AjaxEditableMultiLineLabel 是一个包含两个组件的面板:
任何 Ajax 行为都必须添加到任何这些组件中。在您的情况下,您必须向编辑器添加行为。
(以下完整的工作示例在https://repo.twinstone.org/projects/WISTF/repos/wicket-examples-6.x/browse上)
标记
<h2>Form</h2>
<form wicket:id="form">
<div wicket:id="text"></div>
<input wicket:id="submit" type="submit" value="Send" />
</form>
<hr/>
<h2>Result</h2>
<div wicket:id="result">[result placeholder]</div>
代码片段
final IModel<String> textModel = Model.of("initial text");
Form<String> form = new Form<>("form", textModel);
add(form);
AjaxEditableMultiLineLabel<String> textArea = new AjaxEditableMultiLineLabel<String>(
"text", textModel) {
private static final long serialVersionUID = 1L;
@Override
protected FormComponent<String> newEditor(MarkupContainer parent,
String componentId, IModel<String> model) {
final FormComponent<String> editor = super.newEditor(parent,
componentId, model);
editor.add(new AjaxFormComponentUpdatingBehavior("keyup") {
private static final long serialVersionUID = 1L;
@Override
protected void onUpdate(AjaxRequestTarget target) {
System.out.println("Ajax update for textArea " + editor.getDefaultModelObjectAsString());
}
});
return editor;
}
};
textArea.setCols(50);
textArea.setRows(20);
form.add(textArea);
form.add(new SubmitLink("submit"));
add(new Label("result", textModel));
警告:以前的代码真的很慢
代码很慢,因为每次按键/释放都会产生以下影响:
- 使用 textarea 的内容调用服务器
- 在服务器端调用代码(更新、渲染等)
- 在 XML 响应 (AJAX) 中将整个结果标记作为 html 发回
- 替换整个结果标签
它在本地主机上很慢,在真正的互联网中绝对不可用。
解决方案
使用简单的 jQuery 更新(JavaScript,jQuery 内置在 Wicket 6 中)
带有 jQuery 更新的代码片段
final IModel<String> textModel = Model.of("initial text");
final Label result = new Label("result", textModel);
result.setOutputMarkupId(true);
add(result);
Form<String> form = new Form<>("form", textModel);
add(form);
AjaxEditableMultiLineLabel<String> textArea = new AjaxEditableMultiLineLabel<String>(
"text", textModel) {
private static final long serialVersionUID = 1L;
private boolean initialized = false;
private FormComponent<String> editor;
@Override
public void onEdit(AjaxRequestTarget target) {
super.onEdit(target);
if(!initialized) {
String editorId = editor.getMarkupId();
String resultId = result.getMarkupId();
StringWriter sw = new StringWriter();
sw.write("$('#");
sw.write(editorId);
sw.write("').keyup(function() { var str = $('#");
sw.write(editorId);
sw.write("').val(); ");
sw.write("$('#");
sw.write(resultId);
sw.write("').html(str); });");
String js = sw.toString();
System.out.println("Appending editor JS " + js);
target.appendJavaScript(js);
initialized = true;
}
}
@Override
protected FormComponent<String> newEditor(MarkupContainer parent,
String componentId, IModel<String> model) {
editor = super.newEditor(parent, componentId, model);
return editor;
}
};
textArea.setCols(50);
textArea.setRows(20);
form.add(textArea);
form.add(new SubmitLink("submit"));