本文介绍了Wicket:在哪里添加组件?构造函数?还是onBeforeRender?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Wicket newb。这可能只是我对Wicket生命周期的无知所以请赐教!我的理解是Wicket WebPage 对象被实例化一次然后被序列化。这让我感到困惑,见下文。

I'm a Wicket newb. This may just be my ignorance of the Wicket lifecycle so please enlighten me! My understanding is that Wicket WebPage objects are instantiated once and then serialized. This has led to a point of confusion for me, see below.

目前我有一个模板类,我打算将其子类化。我按照Wicket文档中的示例演示了如何在子类中覆盖模板的行为:

Currently I have a template class which I intend to subclass. I followed the example in the Wicket docs demonstrating how to override the template's behavior in the subclass:

protected void onBeforeRender() {
        add(new Label("title", getTitle()));

        super.onBeforeRender();
}

protected String getTitle() {
        return "template";
}

子类:

protected String getTitle() {
        return "Home";
}

这非常有效。我不清楚的是这方面的最佳实践。似乎 onBeforeRender()在页面的每个请求上都被调用,不是吗?如果所有内容都在 onBeforeRender()中,这似乎会在页面上完成更多的处理。我可以很容易地跟随其他Wicket示例的示例,并在构造函数中添加一些我不想覆盖的组件,但后来我将组件逻辑划分为两个位置,这是我犹豫不决的事。

This works very well. What's not clear to me are the "best practices" for this. It seems like onBeforeRender() is called on every request for the page, no? This seems like there would be substantially more processing done on a page if everything is in onBeforeRender(). I could easily follow the example of the other Wicket examples and add some components in the constructor that I do not want to override, but then I've divided by component logic into two places, something I'm hesitant to do.

如果我添加一个我打算在所有子类中的组件,我应该将它添加到构造函数中还是 onBeforeRender()

If I add a component that I intend to be in all subclasses, should I add it to the constructor or onBeforeRender()?

推荐答案

对于非 Page 的组件,您可以覆盖新的 onInitialize 回调添加组件,只有在构造完成后才会调用组件,此时组件已添加到页面中(以便 component.getPage( )不返回 null )。

For components that are not a Page, you can override the new onInitialize callback to add components, which is only called once after construction, when the component has been added to the page (so that component.getPage() doesn't return null).

另一种选择是使用 addOrReplace()而不是添加

Another option is to use addOrReplace() instead of add.

至于调用被覆盖构造函数中的方法,尝试在模型或其他一些延迟回调中执行此操作。在您的示例中,解决方案更简单:

As for calling overridden methods in a constructor, try to do that in a Model or some other delayed callback. In your example the solution is much simpler:

public abstract class BasePage extends WebPage {
    public BasePage() {
        add(new Label("title", new PropertyModel<String>(this, "title")));
    }
    public abstract String getTitle();
}

使用 PropertyModel 检索标签的内容比将值推入标签要好得多。

Using a PropertyModel to retrieve the contents of the label is much better than pushing the value into the label.

这篇关于Wicket:在哪里添加组件?构造函数?还是onBeforeRender?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 23:58