Question

I am very new to jquery and recently tailored the jquery combobox as per my needs. However, I need to reuse this component in other places on my site. I essentially need to pass in some arguments and a callback function which should be called for handling certain events in jquery. I'm struggling with the syntax and trying to find jquery-way of doing things:

To give you a sample, here is the source of combobox -> input -> autocomplete -> source:

(Created a working jsfiddle for reference)

source: function( request, response ) {
    // implements retrieving and filtering data from the select
    var term = request.term;
    var prefixLength = 2;
    if (term.length >= prefixLength) {
        var abbreviation = term.substring(0, prefixLength);

        if(!(abbreviation.toLowerCase() in cache)){
            cache[abbreviation.toLowerCase()] = 1;

            $.ajax({
                url: "/wah/destinationsJson.action",
                dataType: "json",
                data: {
                    term: abbreviation
                },
                type: "GET",
                success: function(data) {
                    if(!data || !data.cities || !data.cities.length){
                        // response(["No matches for " + term]);
                        return;
                    } 
                    updateOptions(select, data.cities);
                    response(filterOptionsForResponse(select, term));
                    return;
                }
            });
        }
    }

    response(filterOptionsForResponse(select, term));
}

Here updateOptions(...), filterOptionsForResponse(select, term) are simple javascript functions.

In order to reuse, I need to specify a callback to handle source for every instance of combobox that I create.

Can someone point me in the right direction on how to do this ?

Was it helpful?

Solution

The only useful widget factory documentation is in the wiki and that says:

Properties:
[...]
this.options
The options currently being used for the plugin configuration. On instantiation, any options provided by the user will automatically be merged with any default values

So if you needed to supply a callback function for source, then you'd say this:

$("#searchbox").combobox({
    source: function(request, response) { /* ... */ }
});

and then inside your plugin, look at this.options.source:

$.widget("ui.combobox", {
    options: {
        // Default options go here...
    },
    _create: function() {
        //...
        input = $("<input>").appendTo(wrapper).val(value).addClass("ui-state-default").autocomplete({
            source: this.options.source,
            //...

You don't have to include the default options but it almost always makes sense to do so (even if you just use it for documentation purposes).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top