代码之家  ›  专栏  ›  技术社区  ›  Clayton

Wicket:从IBehavior::OnComponentTag更改组件主体

  •  0
  • Clayton  · 技术社区  · 14 年前

    我正在实现wicket-i behavior接口,希望我的行为从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>
    
    2 回复  |  直到 14 年前
        1
  •  2
  •   Don Roby    14 年前

    您可以通过从组件中获取模型、从模型中获取对象以及对对象进行所需的任何更改来实现这一点,但是 onComponentTag 不是改变模型的最佳工作场所。

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

    如果您试图更改渲染体,这是另一个故事,并且在这种方法中要做的工作是完全合理的。它通常涉及调用 ComponentTag tag 参数。

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

    编辑:

    对于裁剪标签上显示的特定情况,只需将 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);
        }
    }
    
        2
  •  2
  •   mfunk    14 年前

    源于快速启动 http://wicket.apache.org/start/quickstart.html 我的建议如下:

        add(new Label("message", "If you see this message wicket is properly configured and running") {
    
            @Override
            protected void onComponentTagBody(MarkupStream markupStream, ComponentTag openTag) {
                String myAttrib = openTag.getAttribute("myAttrib");
                replaceComponentTagBody(markupStream, openTag, getDefaultModelObjectAsString().substring(0, Integer.valueOf(myAttrib)));
            }
    
        });
    

    不过别忘了注意数字格式例外。

    同时,多罗比的建议也很有效。如果不需要的话,不要乱弄模型。