在 AjaxLink 中依次调用几个不同的 JavaScript

Call several different JavaScript within AjaxLink one after the other

当我点击 AjaxLink 时,我想先在客户端通过 JavaScript 进行验证(因为查询了 LocalStorage),然后根据结果进一步 JavaScript打电话。我怎样才能做到这一点? 在伪代码中,它看起来像这样:

new AjaxLink<>("myId", myModel) {

    @Override
    public void onClick(AjaxRequestTarget target) {
        boolean isCounterValid = target.appendJavaScript(checkCounter()); // i know that this is not possible, therefore pseudo code
        if(isCounterValid) {
            target.appendJavaScript(someOtherJavaScript());
        }
        else {
            target.appendJavaScript(anotherJavaScript());
        }
    }

    private String checkCounter() {
        return "var count = window.localStorage.getItem('myCounter'); return count !== 1;";
    }

    private String someOtherJavaScript() {
        return "change something";
    }

    private String anotherJavaScript() {
        return "change other thing";
    }
};

AJAX 组件和行为可以自定义 AJAX 属性来覆盖 updateAjaxAttributes 并使用 AjaxCallListener 的自定义实现,它公开了不同的方法来连接到 AJAX 请求周期。在您的情况下,您可以使用 AjaxCallListener#getBeforeSendHandler。 有关此主题的完整介绍(带示例),请参阅用户指南:

https://ci.apache.org/projects/wicket/guide/8.x/single.html#_ajax_request_attributes_and_call_listeners

单击 link 时,您需要使用 Ajax 调用发送额外的请求参数。为此,您应该覆盖 AjaxLink:

updateAjaxAttributes(AjaxRequestAttributes attributes) 方法
@Override
protected void updateAjaxAttributes(AjaxRequestAttributes attributes)
{
   attributes.getDynamicExtraParameters().add("var count = window.localStorage.getItem('myCounter'); return [{\"name\":\"count\", \"value\": count}]");
}

这样进入 AjaxLink#onClick() 您可以通过以下方式读取计数:

int count = getRequest().getRequestParameters().getParameterValue("count").toInt();