Search code examples
ajaxwicketwicket-6

Wicket 6: Howto inject a javascript function via AbstractDefaultAjaxBehavior?


I have a page that has a JavaScript file attached to it.

The JavaScript has a function that, at the end should call a function that has been injected by Wicket through AbstractDefaultAjaxBehavior.

The JavaScript looks like this:

function updateAmount(amount){
  // do some calculations on amount
  saveAmount(amount);
}

The injected function should look something like this:

function saveAmount(amount){
  Wicket.Ajax.post({
    u: '${callbackUrl}',
    dep: function(){
           return [{name:'amount','value':amount}];
         }
}

The problem I have is that when updateAmount calls the saveAmount function the (console) log states that the "saveAmount" is undefined.

If I look at the source, the injected function is there but not as JavaScript but as "AJAX" JavaScript generated by wicket.

The goal is to call a function in JavaScript that will call a function injected by Wicket that performs an AJAX call with parameters that are provided by JavaScript.

I would really appreciate any help.


Solution

  • Basically, you should use the updateAjaxAttributes() and renderHead() in a custom AbstractAjaxBehaviour

    See for more detail here:

    http://wickedsource.org/2013/01/07/rolling-your-own-ajax-behavior-with-wicket/

    Retrieved from google cache, relevant code (written by Tom Hombergs):

    public class MyAjaxBehavior extends AbstractDefaultAjaxBehavior {
    
    @Override
    protected void respond(AjaxRequestTarget target) {
    RequestCycle cycle = RequestCycle.get();
    WebRequest webRequest = (WebRequest) cycle.getRequest();
    StringValue param1 = webRequest.getQueryParameters().getParameterValue("param1");
    StringValue param2 = webRequest.getQueryParameters().getParameterValue("param2");
    // do whatever you need with param1 and param2
    }
    
    @Override
    public CharSequence getCallbackScript() {
    String script = super.getCallbackScript().toString();
    script = script.replace("\"PLACEHOLDER1\"", "param1Value");
    script = script.replace("\"PLACEHOLDER2\"", "param2Value");
    return script;
    }
    
    @Override
    protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
    super.updateAjaxAttributes(attributes);
    attributes.getExtraParameters().put("param1", "PLACEHOLDER1");
    attributes.getExtraParameters().put("param2", "PLACEHOLDER2");
    }
    
    @Override
    public void renderHead(Component component, IHeaderResponse response) {
    super.renderHead(component, response);
    String script = "var param1Value = My.JavaScript.Module.calculate1();";
    script += "var param2Value = My.JavaScript.Module.calculate2();";
    script += getCallbackScript();
    response.render(OnDomReadyHeaderItem.forScript(script));
    }
    
    }