Wicket:如果页面模型已更改,请通知

Jiv*_*ngs 6 java wicket

问题是这样的; 网页包含多个表单元素,用户可以通过保存按钮更改和保存,或者可以丢弃更改.

如果用户试图离开页面而不保存更改,我需要一个模态窗口来询问用户是否要在离开页面之前保存更改.

我如何检查用户自首次加载以来是否更改了页面/表单模型,以及如何在单击任何页面链接时启动此检查?

任何回应或建议将不胜感激,

谢谢.

Sea*_*oyd 4

我认为您会寻找一种仅使用 javascript 的解决方案,通常打包为 wicket 行为。

实现取决于您使用的 javascript 库,这里是一些原型代码:

var windowdirty = false;
var windowdirtyinitialized = false;

function initwindowdirty(){
    if(windowdirtyinitialized)return;
    windowdirtyinitialized=true;

    Event.observe(window,"beforeunload",function(){
        return (!windowdirty || 
          confirm("You have started entering values, do you really want to leave");
    });
}

function monitor(componentId){
    $(componentId).observe("change",function(){
        windowdirty = true;
    });
}

function undirty(){
    windowdirty=false;
}
Run Code Online (Sandbox Code Playgroud)

我们将其放入名为 DontLeaveBehavior.js 的文件中

以下是使用此 javascript 文件的行为:

public class DontLeaveBehavior extends AbstractBehavior{

    /**
     * {@inheritDoc}
     */
    @Override
    public void renderHead(final IHeaderResponse response){
        response.renderJavascriptReference(new JavascriptResourceReference(DontLeaveBehavior.class,
            "DontLeaveBehavior.js"));
        response.renderOnDomReadyJavascript("initwindowdirty();");
        super.renderHead(response);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void bind(final Component component){
        super.bind(component);
        component.setOutputMarkupId(true);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onRendered(final Component component){
        final Response response = RequestCycle.get().getResponse();
        response.write(JavascriptUtils.SCRIPT_OPEN_TAG);
        response.write("monitor('" + component.getMarkupId() + "');");
        response.write(JavascriptUtils.SCRIPT_CLOSE_TAG);
    }

}
Run Code Online (Sandbox Code Playgroud)

现在,这是一个页面,自动将此行为分配给所有作为文本组件的子元素:

public class Mypage extends WebPage{

    ...

    private boolean behaviorAssigned = false;

    /**
     * {@inheritDoc}
     */
    @Override
    protected void onBeforeRender(){
        if(!behaviorAssigned){
            behaviorAssigned=true;
            visitChildren(new IVisitor<Component>(){

                @Override
                public Object component(Component component){
                    if(component instanceof AbstractTextComponent<?>){
                        component.add(new DontLeaveBehavior());
                    }
                    return null;
                }
            });
        }
        super.onBeforeRender();
    }

}
Run Code Online (Sandbox Code Playgroud)

最后但并非最不重要的一点是,您的提交按钮undirty()当然必须调用。

这些都没有经过测试,因为我现在必须回家与我的妻子和孩子共进晚餐(当然,这比边门编码更有趣),但它应该可以帮助您开始。

原型特定部分应该可以轻松移植到任何其他 javascript 库,但如果您不知道自己在做什么,则可能不应该在没有库的情况下执行此操作。


编辑:

我创建了一个与原型和 mootools 一起使用的新版本,并将其发布在我的博客上。此版本仅安装到表单组件,并通过 javascript 自动将其自身附加到子组件。

再次编辑:那里,现在链接正在工作