Hi there,

I've a problem with appending a part of a javascript code to the head once
for all my concrete behavior classes.
Below what I do at this moment:

JQueryBehavior class
public abstract class JQueryBehavior extends AbstractBehavior {
    private static final String JQUERY_1_2_6 = "res/jquery-1.2.6.pack.js";

    private static final CompressedResourceReference JQUERY_RESOURCE = new
CompressedResourceReference(JQueryBehavior.class, JQUERY_1_2_6);

    @Override
    public void renderHead(IHeaderResponse response) {
        response.renderJavascriptReference(JQUERY_RESOURCE);
        CharSequence script = getOnReadyScript();
        if (StringUtils.isNotBlank((String) script)) {
            StringBuilder sb = new StringBuilder()
                    .append(JavascriptUtils.SCRIPT_OPEN_TAG)
                    .append("\n$(document).ready(function() {\n")
                    .append(script)
                    .append("\n});")
                    .append(JavascriptUtils.SCRIPT_CLOSE_TAG)
                    .append("\n");
            response.renderString(sb.toString());
        }
    }

    protected abstract CharSequence getOnReadyScript();

}

My problem now is that I want the script open en close tags one time to be
appended to the head tag. And just add the script between these two elements
for each behavior I create. Below an example of a behavior that passes his
script to the super class.
Is there any way, maybe something that Wicket already has, to control if
this part of the script already has been added?

BlurFieldBehavior class
public class BlurFieldBehavior extends JQueryBehavior {
    private static final String BLUR_FIELD_SCRIPT = "res/blurField.js";
    private static final String BLUR_FIELD_CSS_CALSS_NAME = "blur-input";

    private static final ResourceReference PLUGINS_RESOURCE = new
JavascriptResourceReference(BlurFieldBehavior.class, BLUR_FIELD_SCRIPT);

    @Override
    protected CharSequence getOnReadyScript() {
        return String.format("\t$('input.%s').blurInput();",
BLUR_FIELD_CSS_CALSS_NAME);
    }

    @Override
    public void onComponentTag(Component component, ComponentTag tag) {
        assert component instanceof TextField;
        tag.addBehavior(new AttributeModifier("class", true, new
Model(BLUR_FIELD_CSS_CALSS_NAME)));
    }

    @Override
    public void renderHead(IHeaderResponse response) {
        super.renderHead(response);
        response.renderJavascriptReference(PLUGINS_RESOURCE);
    }
}

SearchPanel class
...
private TextField createPhoneNumberTextField() {
        TextField phoneNumberTextField = new TextField("phoneNumber", new
Model("Phone number"));
        TextFieldUtils.addMaxLength(phoneNumberTextField, 11);
        phoneNumberTextField.add(new BlurFieldBehavior());
        return phoneNumberTextField;
    }
...

Thank you,

Hbiloo

Reply via email to