我将一个Web应用程序更新为Bootstrap 3和Knockout 3,因此丢失了Bootstrap 2中的内置预先输入。我添加了typeahead.js,除非我在Knockout'foreach'绑定中有一个预先输入,否则它会很有效。我包含了以下工作和失败的代码以及typeahead和Bootstrap绑定的Javascript代码。有什么想法吗?
<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>
用于typeahead.js和Knockout绑定的Javascript
<script>
$( document ).ready(function() {
$('input.sections').typeahead({
name: 'sectionName',
local: [
'ABC',
'DEF'
]
});
ko.applyBindings({
section : [
{ name: "", other: "1234" },
{ name: "", other: "5678" }
]
});
});
</script>
答案 0 :(得分:7)
对于像小部件这样的东西,特别是当你通过模板/控制流渲染元素时,最好的选择是使用自定义绑定来初始化小部件。例如,您可以使用以下内容:
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;
});
}
};
答案 1 :(得分:2)
您应该只覆盖在KO中响应valueUpdate的事件
<input type="text"
class="form-control sectionNames"
data-bind="
value: name,
valueUpdate: 'typeahead:selected typeahead:autocompleted"
/>