Knockout js复选框检查绑定 [英] Knockout js checkbox checked binding
问题描述
在淘汰赛中,我试图对一组数据执行foreach以显示复选框。我遇到的问题是,在我与其中一个框交互之前,检查的数据绑定似乎没有运行。例如,下面我生成5个文本框,其中没有一个显示为已选中。但是当我点击一个时,两个和四个也会被检查,因为它们本应该从一开始。
In knockout js am trying to perform a foreach on an array of data to display check boxes. The issue I am having is that the checked databind does not appear to run until I interact with one of the boxes. For example, below I am generating 5 text boxes none of which are showing up as checked. However when I click "one", "two" and "four" also get checked as they should have been from the beginning.
Javascript:
Javascript:
var viewModel = {};
viewModel.choices = ["one", "two", "three", "four", "five"];
viewModel.selectedChoices = ko.observableArray(["two", "four"]);
viewModel.selectedChoicesDelimited = ko.dependentObservable(function () {
return viewModel.selectedChoices().join(",");
});
ko.applyBindings(viewModel);
HTML:
<ul class="options" data-bind="foreach: choices">
<li><label><input type="checkbox" name="NotifyMembers" data-bind="checked: $parent.selectedChoices, attr: { value: $data }" /><span data-bind="text: $data"></span></label></li>
</ul>
<hr />
<div data-bind="text: selectedChoicesDelimited"></div>
小提琴位于: http://jsfiddle.net/bvGG3/1/
感谢您的帮助。
推荐答案
在版本3.0之前的Knockout中按顺序触发绑定,所以你的问题是你的选中了
绑定在您的 attr
绑定之前触发。
In Knockout before version 3.0 the bindings fired in order, so your problem is that your checked
binding fires before your attr
binding.
因此您需要更改绑定的顺序:
So you need to change the order of your bindings:
<input type="checkbox" name="NotifyMembers"
data-bind="attr: { value: $data }, checked: $parent.selectedChoices" />
演示 JSFiddle 。
或者当您更新到3.0时,您的原始代码将起作用(演示 JSFiddle )。
Or your original code will work when you update to 3.0 (demo JSFiddle).
这篇关于Knockout js复选框检查绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!