JSFiddle - React, Tailwind, and code Playground
by gbos
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/awesomplete/1.0.0/awesomplete.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/awesomplete/1.0.0/awesomplete.min.css">
<!-- https://leaverou.github.io/awesomplete -->
<input type="text" placeholder="country search..." data-bind="awesomplete: fetch">
<hr>
<input type="text" placeholder="country search..." data-bind="awesomplete: list">
JavaScript
ko.bindingHandlers.awesomplete = {
init: function(element, valueAccessor, allBindings) {
var source = ko.unwrap(valueAccessor());
var widget = new Awesomplete(element);
if (Object.prototype.toString.call(source) === '[object Array]') { // list is an array.
widget.list = source;
}
if (typeof source === 'function') { // list is a function
element.addEventListener('keyup', function(evt) {
evt.preventDefault();
if (evt.keyCode === 40 || evt.keyCode === 38) return; // up & down key
if (evt.keyCode === 13) {
widget.close();
return;
}
if (element.value.length >= 3) {
source(element.value, function(list) {
widget.list = list;
});
}
});
}
}
};
ko.applyBindings({
list: ["abricot", "truc", "machin"],
fetch: function(q, done) {
fetch('https://www.mocky.io/v2/566b4071100000203a990c51', {mode: 'cors'}).then(function(resp) {
return resp.json();
}).then(function(resp) {
done(resp.map(function(a) { return a.name; }));
});
}
});
/*
var input = document.querySelector(".awesomplete");
var c = new Awesomplete(input);
input.addEventListener('keyup', function (a) {
console.log(input.value);
if (input.value.length >= 3) {
fetch('https://restcountries.eu/rest/v1/name/'+input.value).then(function (resp) {
return resp.json();
}).then(function (resp) {
c.list = resp.map(function (a) { return a.name; })
});
}
});
*/