Wednesday, July 27, 2011

Google +1 callback and Wicket

Google plusone tag's callback parameter let's you call a JavaScript function when the plusone button is clicked. As an example,

<g:plusone size="tall" callback="callWicket"></g:plusone>
<script type="text/javascript">
        function callWicket(data) {
            // Do something here

What if you want to pass Wicket data (for this example, we'll get the JSON object) when the plusone button is clicked? There's an explanation of calling Wicket from JavaScript. We can either use the wicketAjaxGet or wicketAjaxPost functions provided by the contributed wicket-ajax.js when you add an Ajax behaviour to Wicket components, e.g. adding an AbstractDefaultAjaxBehavior.

We have to build the JavaScript as shown,

function callWicket() {
        var wcall = wicketAjaxGet('$url$' + '$args$', function() { }, function() { });

to be generated by the wicket component :-

<script type="text/javascript" wicket:id="pluscallback"></script>
'$url$' is obtained from behave.getCallbackUrl() and $args will be constructed from plusone JSON object. Thus,
final AbstractDefaultAjaxBehavior behave = new AbstractDefaultAjaxBehavior() {

        protected void respond(final AjaxRequestTarget target) {
            // Do what you want with the data

    CharSequence url = behave.getCallbackUrl();
    CharSequence args = "&href='+data.href+'&state='+data.state";
    StringBuffer sb = new StringBuffer();
    sb.append("function callWicket(data, id) { \n");
    sb.append("     var wcall = wicketAjaxGet('");
    sb.append(url); // the $url$
    sb.append(args); // the $args$
    sb.append(", function() { }, function() { });");
    sb.append("    }");
    Label pluscallback = new Label("pluscallback", sb.toString());   // the script tag
Getting the parameters from the JavaScript

You can download the Wicket quickstart here.

No comments:

Post a Comment