سؤال

How can I dynamically modify the body onload tag of a Wicket 1.6 page in Wicket?

I want to add a JavaScript function to the "onload" attribute that requires dynamic parameters that I generate in Java.

Thanks in advance

هل كانت مفيدة؟

المحلول

It's better to use following approach.

In any component that require some onLoad action to be performed add following method:

@Override
public void renderHead(IHeaderResponse response) {
    super.renderHead(response);
    response.render(
               OnDomReadyHeaderItem.forScript("alert('REPLACE ALERT BY YOUR SCRIPT')"));
}

If you need to prepare script dynamically with extra params and etc. I recommend following:

private final static TextTemplate template 
     = new PackageTextTemplate(YourComponentOrPage.class, "your-js-template.js");
@Override
public void renderHead(IHeaderResponse response) {
    super.renderHead(response);
    Map<String, Object> params =new HashMap<String, Object>();
    params.put("parameter1", parameter1Value);
    params.put("parameter2", parameter2Value);
    response.render(OnDomReadyHeaderItem.forScript(template.asString(params)));
}

And "your-js-template.js" may look like:

alert('Hi!, ${parameter1}. My name is ${parameter2}');

نصائح أخرى

Currently Wicket 6.x has a specific class for onLoad events. No more need for any hackish solutions:

@Override
public void renderHead(IHeaderResponse response)
{
    super.renderHead(response);
    response.render(OnLoadHeaderItem.forScript(yourDynamicScript));
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top