The following seems to work (using wicket 6.7 with the experimental bootstrap 
module).  Basically, this ajax behavior is called on page load.   At that 
point, it writes out the javascript to initialize the object with typeahead 
parameters.  

HTML:

        <input wicket:id="typeahead" type="text" data-provide="typeahead" 
data-items="4">

JAVA:

        add(new TextField<String>("typeahead").add(new TypeAhead()));

TypeAhead Behavior:

import org.apache.wicket.Component;
import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.OnDomReadyHeaderItem;

import java.util.Arrays;
import java.util.List;

public  class TypeAhead extends AbstractDefaultAjaxBehavior {
    @Override
    protected void onBind() {
        super.onBind();
        getComponent().setOutputMarkupId(true);
    }

    @Override
    protected void respond(AjaxRequestTarget target) {
        String sources = toJSONArray(getOptions());
        String script = String.format("$('#%s').typeahead( { source: %s } );", 
getComponent().getMarkupId(), sources);
        target.appendJavaScript(script);
    }

    @Override
    public void renderHead(Component component, IHeaderResponse response) {
        super.renderHead(component, response);
        response.render(OnDomReadyHeaderItem.forScript( 
this.getCallbackScript() ));
    }

     // OVERRIDE THIS TO SUPPLY LIST OF OPTIONS
    public  List<String> getOptions() {
        return Arrays.asList( new String[] {"Alabama", "Aftermath", "Absinth"} 
);
    }

     // There's probably a built-in method that does this…

    private String toJSONArray(List<String> strings) {
        StringBuffer result = new StringBuffer("[");
        for (String string : strings) {
            result.append("'");
            result.append(string);
            result.append("',");
        }
        if (strings.size() > 0) {
            result.deleteCharAt(result.lastIndexOf(","));
        }
        result.append("]");
        return result.toString();
    }

}


Hope this works for you.

-- Don Ferguson


On Tuesday, May 14, 2013 at 1:36 PM, William Speirs wrote:

> I'm trying to create a typeahead component for Wicket that uses Bootstrap's
> Typeahead:
>  
> To set this up though I need to provide the .typeahead method in JavaScript
> with a function that will return the results, given the query. What I'd
> like to do is attach that JavaScript function to a Java method much like
> what is done with an AjaxEventBehavior [2]. I cannot figure out how to go
> about setting all of this up... any ideas?
>  
> Thanks...
>  
> Bill-
>  
> [1] http://twitter.github.io/bootstrap/javascript.html#typeahead
> [2]
> http://ci.apache.org/projects/wicket/apidocs/6.x/org/apache/wicket/ajax/AjaxEventBehavior.html
>  
>  


Reply via email to