2013-11-27 30 views
1

我在Apache Wicket中的JavaScript事件“onbeforeunload”有问题。onpaforeunload事件与Apache Wicket

我想要做的是:我有一个变量,告诉我数据是否发生了变化。现在我想打开JavaScript确认对话框(确认(“我的文本”);)询问用户是否确定他正在失去他的更改。 只有改变了某个对话框才会弹出。

有没有人知道行为是如何工作正确的?

我tryed这一点:

add(new AjaxEventBehavior("onbeforeunload") { 

    @Override 
    protected void onEvent(AjaxRequestTarget target) { 
     target.prependJavaScript("confirm('my dialog');"); 
    } 
}); 

做些什么:我现在得到两个对话框。第一个是其中包含文字“假”的对话框。第二个是我真正的对话。

有没有人有此事件的经验?

回答

3

迈克尔,我看你有一个错误的介词onbeforeunload如何工作,你在哪里AjaxEventBehavior。

AjaxEventBehavior将监听器添加到javascript事件中。您可以使用众所周知的元素'onclick','onchange'等事件。第二种方法是使用您自己的事件,例如, 'myevent'并从javascript中触发它。这两种情况意味着您将AjaxEventBehavior添加到HTML元素(如“DIV”,“A”等)。

但是,事件'onbeforeunload'实际上是另一种情况,因为它是由窗口定义的事件,所以它是'window.onbeforeunload'。

最简单的方法之一是创建一个HTML元素并添加一个自定义事件。然后在页面的head部分添加一个javascript,将刚刚定义的事件的触发器添加到onbeforeunload。

实施例:

检票1.6

标记

<div wicket:id="myElement">[just a placeholder tag]</div> 

代码示例:

static String CUSTOM_EVENT_NAME = "myElementEvent"; 

add(new WebMarkupContainer("myElement") 
{ 
    private static final long serialVersionUID = 1L; 

    @Override 
    public void renderHead(IHeaderResponse response) 
    { 
     super.renderHead(response); 
     StringWriter sw = new StringWriter(); 
     sw.append("$(window).bind('onbeforeunload', function() { $('#"); 
     sw.append(getMakupId()); 
     sw.append("').trigger('"); 
     sw.append(CUSTOM_EVENT_NAME); 
     sw.append("'); });"); 
     response.render(OnDomReadyHeaderItem.forScript(sw.toString())); 
    } 

} 
.setOutputMarkupId(true) 
.add(
    new AjaxEventBehavior(CUSTOM_EVENT_NAME) 
    { 
     private static final long serialVersionUID = 1L; 

     protected void onEvent(final AjaxRequestTarget target) 
     { 
     // your code 
     } 
    }) 
); 
+0

你怎么会在检票1.5做到这一点的BasePage 0.1? – user2340939

0

使用Wicket 1.3.7我解决了这个问题是这样的:

protected static final String EVENT_ON_UNLOAD = "onunload"; //Be shure eventname is lowercase only 

body = new WebMarkupContainer("_body_") 
{ 
    @Override 
    public void renderHead(HtmlHeaderContainer container) 
    { 
     super.renderHead(container); 

     StringWriter sw = new StringWriter(); 
     sw.append("window.addEventListener('beforeunload', function(e) { $('#"); 
     sw.append(body.getMarkupId()); 
     sw.append("').trigger('"); 
     sw.append(EVENT_ON_UNLOAD); 
     sw.append("'); });"); 

     String javascript = sw.toString(); 
     IHeaderResponse response = container.getHeaderResponse(); 
     response.renderOnDomReadyJavascript(javascript); 
    } 
}; 
body.setOutputMarkupId(true); 
body.add(new AjaxEventBehavior(EVENT_ON_UNLOAD) 
{ 
    protected void onEvent(final AjaxRequestTarget target) 
    { 
     // your Code 
    } 
}); 
add(body); 

我把它添加到其简化看起来像这样

<html> 
 
    <head> 
 
    ... 
 
    </head> 
 

 
    <body wicket:id="_body_"> 
 
    ... 
 
    </body> 
 
</html>