Wednesday, May 23, 2012

Wicket Notification Dialog - JavaScript refactoring

This blog contains update to Wicket - Disappearing Notification Dialog post.
I've moved JavaScript from Java code to separate file - it is in general good patern to not mix up those.


Previous post has following JavaScript:
effectBehavior.setCallback(new JQueryAjaxBehavior(this) {

    @Override
    public CharSequence getCallbackScript() {
        String fadeOut = "function(){$('" + dialogContainerId + ":visible').fadeOut();}";
        String callbackScript = "setTimeout(" + fadeOut + ", "
                        + Long.toString(config.getNotificationDisplayTimeMilis()) + ");";
        return callbackScript;
    }
});
Now we will move this JavaScript to notifier.js file, define there JS functions and call those functions from Java code.
notifier.js
function fadeOutDialog() {
    $("${dialogContainerId}:visible").fadeOut();
}

function playBounce() {
    setTimeout(fadeOutDialog, "${notificationDisplayTimeMilis}");
}
and modified getCallbackScript method:
effectBehavior.setCallback(new JQueryAjaxBehavior(this) {

    @Override
    public CharSequence getCallbackScript() {
        return "playBounce()";
    }
});
Additionally to execute playBounce() from notifier.js we need to register it on our HTML page and pass arguments  ${dialogContainerId} and ${notificationDisplayTimeMilis}
We will create JavaScriptTemplate as global variable in Notifier class, and overwrite renderHead  method which will append JavaScript into page header and also will set required properties:
    private JavaScriptTemplate notifierJs = 
      new JavaScriptTemplate(new PackageTextTemplate(Notifier.class, "notifier.js"));

    @Override
    public void renderHead(IHeaderResponse response) {
        Map<String, String> cssVariables = new HashMap<String, String>();
        cssVariables.put("dialogContainerId", dialogContainerId);
        cssVariables.put("notificationDisplayTimeMilis", 
                   Integer.toString(config.getBounceTimeMilis()));
        response.renderString(notifierJs.asString(cssVariables));
    }

No comments:

Post a Comment