0

I have a feeling this is going to be a quick and easy one for most, but for me at least, the solution is proving elusive.

I'm extending the jQuery autocomplete widget to include some functionality as default. I need to reference this.options.primaryField in the select event.

$.widget( "mynamespace.myAutoComplete", $.ui.autocomplete, {
    options: {
        // our options
        selectedId:0,
        searchString:'',
        indexField:'',
        primaryField:'',
        secondaryField:'',

        // set existing ones
        autoFocus: true,
        minLength:3,

        select: function(event,ui) {
            // runs, but cant access this.options.<anything>
        }

    },

    _myselect: function (event,ui) {
        //does not run
        console.log("in myselect");
    },

    _renderItem: function (ul, item) {
        var icon='marker';
        return $("<li>")
            .append ('<div><a><i class=\"fi-' + icon + '"></i>' + item[this.options.primaryField] + "<br>" + item[this.options.secondaryField] + "</a><div>")
            .appendTo (ul);
    }
}); 

I've found potential solutions here: Howto access data held in widget options when inside a widget event handler, jQuery Widget Factory access options in a callback method and jQuery-ui: How do I access options from inside private functions

But I can't get any of them to work. This is the code I've derived from those solutions: (Naturally adding it to the $.widget(... class )

_create: function() {

        // does not fire _myselect on select
        this._on(this.select, { change: "_myselect"});
        this._on(this.select, $.proxy(this._myselect, this));
        this._on(this.select, $.bind(this._myselect, this));

        this._super();
    },

I've also tried adding those to the _init function as well. I just want to be able to set this.options.selectedId, searchString, etc when an Item is clicked.

Thanks in advance

Community
  • 1
  • 1
GeoSword
  • 234
  • 1
  • 13

1 Answers1

0

Finally nailed this. For anyone else hitting the same problem:

$.widget( "ui.autocomplete", $.ui.autocomplete, {
_init: function() {
    this.element.on("autocompleteselect", $.proxy(this.myselect, this));
},
options: {
    // our options
    selectedId:0,
    searchString:'',
    indexField:'',
    primaryField:'',
    secondaryField:'',
    ....
},
myselect: function (event, ui) {
    // event and ui work as normal
    // this, refers to the widget, so the options are available via
    // this.options.<blah>
}

I should also point out that the name space I chose in the question also seemed to have played a part in the problem. If I use anything other than ui.autocomplete (which I presume will make an unmodified autocomplete inaccessible where-ever I have this code) the event fails to fire. That said, even with the namespace as ui.autocomplete, the three this._on.. commands I mentioned in the question still failed

GeoSword
  • 234
  • 1
  • 13