gpt4 book ai didi

java - Wicket:从 IBehavior::onComponentTag 更改组件主体

转载 作者:行者123 更新时间:2023-12-01 19:21:41 26 4
gpt4 key购买 nike

我正在实现 Wicket IBehavior 接口(interface),并希望我的行为通过 onComponentTag 方法更改组件的主体(或以某种方式更新模型)。有办法做到这一点吗?

@Override
public void onComponentTag(final Component component, final ComponentTag tag)
{
String myValue = tag.getAttribute("myAttribute");

// TODO: Based on the value of this attribute, update the body/model of the component


super.onComponentTag(component, tag);
}

编辑:我想从 html 中获取一个属性,该属性指定元素允许的最大字符数,然后根据需要以编程方式截断元素的主体。

示例:

<span wicket:id="myLabel" maxChars="10">The body of my tag</span>

将替换为:

<span wicket:id="myLabel" maxChars="10">The bod...</span>

最佳答案

您可以通过从组件获取模型、从模型获取对象并对对象进行所需的任何更改来完成此操作,但 onComponentTag 并不是最佳工作场所这会改变模型。

此方法在渲染过程中调用,此时您的页面可能已部分渲染。已呈现的页面的任何部分都将使用模型的先前状态进行呈现。由于模型可以在组件之间共享,因此生成的页面可能会不一致。

如果您尝试更改渲染的主体,那是另一个故事,并且在此方法中完成的工作完全合理。它通常涉及调用 ComponentTag 标记 参数上的方法。

您试图通过创建此行为来解决什么问题?也许我们可以想出更好的办法。

编辑:

对于修剪标签上显示的特定情况,您可能最好通过简单地子类化 Label 组件,大致如下:

public class TrimmedLabel extends Label {
private int size;

public TrimmedLabel(String id, int size) {
super(id);
this.size = size;
}

public TrimmedLabel(String id, String label, int size) {
super(id, label);
this.size = size;
}

public TrimmedLabel(String id, IModel model, int size) {
super(id, model);
this.size = size;
}

@Override
protected void onComponentTagBody(MarkupStream markupStream, ComponentTag openTag) {
String value = getModelObjectAsString();
if (value.length() > size) {
value = value.substring(0, size);
}
replaceComponentTagBody(markupStream, openTag, value);
}
}

关于java - Wicket:从 IBehavior::onComponentTag 更改组件主体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3963369/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com