JQueryUI Autocomplete-Widget: I want to bind a function to the select event of a menu widget

I have the following script using jQueryUI autocomplete widget. It calls some function whenever a menu item in the selection window is selected:

<script type="text/javascript">
    $(function() {
        $( "#tags" ).autocomplete({
            source: [ "ActionScript", "AppleScript", "Asp"],
            select: function() { 
                console.log("Element has been selected");
            }
        });
    });
</script>

<div class="ui-widget">
    <label for="tags">Tags: </label>
    <input id="tags">
</div>

It works well. But I need this method in multiple instances of the autocomplete widget, so I prefer to extend the autocomplete widget using the factory widget .

This works well when I want to override the autocomplete plugin methods:

$.widget("ui.myAutocomplete", $.extend({}, $.ui.autocomplete.prototype, {
    search: function( value, event ) {
        // this WORKS!
        console.log('overriding autocomplete.search')

        return $.ui.autocomplete.prototype.search.apply(this, arguments);
    }
}));

However, I do not know how to do this for the main menu widget.

_init select. , , bind ( )

$.widget("ui.myAutocomplete", $.extend({}, $.ui.autocomplete.prototype, {
    _init: function() {
        // this does NOT work. 
        this.bind('select', function() { console.log('item has been selected') })

        return $.ui.autocomplete.prototype._init.apply(this, arguments);
    }
}));
+3
1

, ; _create _init:

$.widget("ui.myAutocomplete", $.extend({}, $.ui.autocomplete.prototype, {
    _create: function() {
        // call autocomplete default create method:
        $.ui.autocomplete.prototype._create.apply(this, arguments);

        // this.element is the element the widget was invoked with
        this.element.bind("autocompleteselect", this._select);
    },
    _select: function(event, ui) {
        // Code to be executed upon every select.
    }
}));

:

$("input").myAutocomplete({
    /* snip */
});

: http://jsfiddle.net/EWsS4/

+3

All Articles