I updated a web app to Bootstrap 3 and Knockout 3 and consequently lost the built in typeahead that was in Bootstrap 2. I added typeahead.js and it works great unless I have a typeahead within a Knockout 'foreach' binding. I included code that works and fails below along with the Javascript code for the typeahead and Bootstrap binding. Any ideas?
<form role="form">
<div class="row">
<div class="col-sm-4 form-group">
<input type="text" class="form-control sectionNames" data-bind="value: name" />
</div>
</div>
<div data-bind="foreach: section">
<div class="row">
<div class="col-sm-4 form-group">
<input type="text" class="form-control sectionNames" data-bind="value: name" />
</div>
</div>
</div>
</form>
Javascript for typeahead.js and Knockout bindings
<script>
$( document ).ready(function() {
$('input.sections').typeahead({
name: 'sectionName',
local: [
'ABC',
'DEF'
]
});
ko.applyBindings({
section : [
{ name: "", other: "1234" },
{ name: "", other: "5678" }
]
});
});
</script>
Your best bet for something like a widget, especially when you are rendering elements via templating/control-flow, is to use a custom binding to initialize the widget. For example, you could use something like this:
ko.bindingHandlers.typeahead = {
init: function(element, valueAccessor) {
var options = ko.unwrap(valueAccessor()) || {},
$el = $(element),
triggerChange = function() {
$el.change();
}
//initialize widget and ensure that change event is triggered when updated
$el.typeahead(options)
.on("typeahead:selected", triggerChange)
.on("typeahead:autocompleted", triggerChange);
//if KO removes the element via templating, then destroy the typeahead
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
$el.typeahead("destroy");
$el = null;
});
}
};
Here is a sample: http://jsfiddle.net/rniemeyer/uuvUR/
You should just override events which respond for valueUpdate in KO
<input type="text"
class="form-control sectionNames"
data-bind="
value: name,
valueUpdate: 'typeahead:selected typeahead:autocompleted"
/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With