简体   繁体   English

Knockout js复选框检查绑定

[英]Knockout js checkbox checked binding

In knockout js am trying to perform a foreach on an array of data to display check boxes. 在淘汰赛中,我试图对一组数据执行foreach以显示复选框。 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. 例如,下面我生成5个文本框,其中没有一个显示为已选中。 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: 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>

Fiddle is at: http://jsfiddle.net/bvGG3/1/ 小提琴在: http//jsfiddle.net/bvGG3/1/

Thanks for your help. 谢谢你的帮助。

In Knockout before version 3.0 the bindings fired in order, so your problem is that your checked binding fires before your attr binding. 在版本3.0之前的Knockout中,绑定按顺序触发,因此您的问题是在您的attr绑定之前触发了已checked绑定。

So you need to change the order of your bindings: 所以你需要改变绑定的顺序:

<input type="checkbox" name="NotifyMembers" 
       data-bind="attr: { value: $data }, checked: $parent.selectedChoices" />

Demo JSFiddle . 演示JSFiddle

Or your original code will work when you update to 3.0 (demo JSFiddle ). 或者,当您更新到3.0(演示JSFiddle )时,您的原始代码将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM