JSFiddle - React, Tailwind, and code Playground
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.10.1/typeahead.bundle.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/knockout/3.0.0/knockout-min.js"></script>
<div>
<h3>Standard typeahead.js control</h1>
<input type="text" class="typeahead" />
</div>
<div>
<h3>My control</h1>
<input type="text" data-bind="typeahead: { name: 'something', taOptions: theseOptions, displayKey: 'Name()' }, value: thisValue" />
</div>
<button data-bind="click: addNew">Add new Option</button>
JavaScript
ko.bindingHandlers.typeahead = {
init: function (element, valueAccessor) {
var options = ko.unwrap(valueAccessor()) || {},
$el = $(element),
triggerChange = function () {
$el.change();
}
options.source = options.taOptions.ttAdapter();
console.log('options local set - ', options.taOptions.ttAdapter);
var thisTypeAhead = $el.typeahead({ minLength: 1 }, options)
.on("typeahead:selected", triggerChange)
.on("typeahead:autocompleted", triggerChange);
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$el.typeahead("destroy");
$el = null;
});
}
};
var numbers = new Bloodhound({
datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.num); },
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: [
{ num: 'one' },
{ num: 'two' },
{ num: 'three' },
{ num: 'four' },
{ num: 'five' },
{ num: 'six' },
{ num: 'seven' },
{ num: 'eight' },
{ num: 'nine' },
{ num: 'ten' }
]
});
// initialize the bloodhound suggestion engine
numbers.initialize();
// instantiate the typeahead UI
$('.typeahead').typeahead(null, {
displayKey: 'num',
source: numbers.ttAdapter()
});
function Option(id, name) {
var self = this;
self.Id = ko.observable(id);
self.Name = ko.observable(name);
}
function viewModel() {
var self = this;
self.thisValue = ko.observable();
self.someOptions = ko.observableArray([
new Option(1, 'John'),
new Option(2, 'Johnny'),
new Option(3, 'Billy')
]);
self.theseOptions = new Bloodhound({
datumTokenizer: function(d) {
var seomth = Bloodhound.tokenizers.whitespace(d.Name());
console.log(seomth);
return seomth },
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: self.someOptions()
});
...