问题
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>
回答1:
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/
回答2:
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"
/>
来源:https://stackoverflow.com/questions/20479698/typeahead-js-not-working-in-knockout-3-foreach-binding