Javascript 更新绑定到表单表的ObservalArray会导致焦点丢失
我正在将一个Javascript 更新绑定到表单表的ObservalArray会导致焦点丢失,javascript,knockout.js,Javascript,Knockout.js,我正在将一个observearray绑定到一个模板,该模板为数组中的每个项生成一个带有的表。其思想是,当用户在最后一行输入文本时,页面会自动添加另一行;它是一个动态扩展的条目列表 这一切都很好,但发生这种情况时键盘焦点会丢失。我发布了损坏的示例,其中包含以下内容: function ingredientViewModel(name, qty, note) { this.name = ko.observable(name); this.quantity = qty; thi
observearray
绑定到一个模板,该模板为数组中的每个项生成一个带有
的表。其思想是,当用户在最后一行输入文本时,页面会自动添加另一行;它是一个动态扩展的条目列表
这一切都很好,但发生这种情况时键盘焦点会丢失。我发布了损坏的示例,其中包含以下内容:
function ingredientViewModel(name, qty, note) {
this.name = ko.observable(name);
this.quantity = qty;
this.note = note;
}
var viewModel = {
ingredients: ko.observableArray([]),
};
// When last ingredient's name changes,
// Add a new row to the list
// Update the global subscription to point to the new item
function lastIngredientNameChanged(newValue) {
var currentfocus = document.activeElement;
if (newValue != '') {
lastIngredientSubscription.dispose();
viewModel.ingredients.push(new ingredientViewModel('', '', ''));
lastIngredientSubscription = viewModel.ingredients()[viewModel.ingredients().length - 1].name.subscribe(lastIngredientNameChanged);
}
currentfocus.focus();
}
// Set up initial entries
viewModel.ingredients.push(new ingredientViewModel('', '', ''));
var lastIngredientSubscription = viewModel.ingredients()[viewModel.ingredients().length - 1].name.subscribe(lastIngredientNameChanged);
ko.applyBindings(viewModel);
此视图代码为:
姓名金额
注{
{
每种成分
}
}
{
{
/每个}}
有什么想法吗?问题是,当您使用{{each}}和您正在循环更改的ObservalArray时,整个模板将重新呈现。因此,您的
currentfocus
元素实际上已经不存在了
您可以切换到使用模板绑定的foreach
选项,该选项只会重新呈现模板中更改的行。您的HTML将如下所示:
<script type="text/html" id="ingredientTemplate">
<table id="ingredienttable">
<colgroup>
<col width="200"/>
<col width="40"/>
<col/>
</colgroup>
<thead><tr>
<td>Name</td>
<td>Amount</td>
<td>Note</td>
</tr></thead>
<tbody data-bind="template: { name: 'rowTmpl', foreach: ingredients }">
</tbody>
</table>
</script>
<script id="rowTmpl" type="text/html">
<tr class="ingrediententry">
<td><input class="ingredientautocomplete" data-bind="value: name, valueUpdate: 'afterkeydown'" /></td>
<td><input data-bind="value: quantity" /></td>
<td><input data-bind="value: note" /></td>
</tr>
</script>
<div data-bind="template: 'ingredientTemplate'"></div>
名称
数量
注
此处示例:
如果你这样做的话,你甚至不需要跟踪currentfocus,它将保持不变