I would like to use JQuery.UI.Autocomplete
component in my module for Magento 2
.
Also, I am using KO.js for the user interface of my application.
So, I have added a custom binding for KO:
define([
'ko',
'jquery',
'jquery/ui'
], function (ko, $) {
'use strict';
ko.bindingHandlers.autoComplete = {
init: function (element, valueAccessor) {
var settings = valueAccessor();
var selectedOption = settings.selected;
var options = settings.options();
var updateElementValueWithLabel = function (event, ui) {
event.preventDefault();
$(element).val(ui.item.label);
if(typeof ui.item !== "undefined") {
selectedOption(ui.item);
}
};
$(element).autocomplete({
source: options,
select: function (event, ui) {
updateElementValueWithLabel(event, ui);
},
focus: function (event, ui) {
updateElementValueWithLabel(event, ui);
},
change: function (event, ui) {
updateElementValueWithLabel(event, ui);
}
});
}
};
});
I've added the following code in my html template:
<div class="suggestions">
<input id="suggestion_box" type="text" data-bind="autoComplete: { selected: $data.productSuggestions.selectedSuggestion, options: $data.productSuggestions.suggestions }" />
</div>
It looks good, but it doesn't work. I've got a error message in the browser console. I debugged it and as it turned out, the reason of the issue is in the following lines(they start from the 6819
line) of jquery-ui.js
library:
this.menu = $( "<ul>" )
.addClass( "ui-autocomplete ui-front" )
.appendTo( this._appendTo() )
.menu({
// disable ARIA support, the live region takes care of that
role: null
})
.hide()
.data( "ui-menu" );
The this.menu
field is undefined, because of invoking data( "ui-menu" )
method. Methods that invoke before data()
one are returns their results.
It seems like I've inited JQuery.UI.Autocomplete
in a wrong way, but all examples of configuring are quite simple and I'm not sure what have I done wrong.
Any ideas?