[英]KO radio works but does not initialise as checked
Here's a snippet from a knockout based answer editor 这是基于基因剔除的答案编辑器的摘录
<!-- ko foreach: Answers -->
<div class="qa-box" data-bindx="event: { mousedown: mouseDown, dragend: dragEnd, dragstart: dragStart }">
<div class="qa-body">
<div class="radio">
<label>
<input type="radio" data-bind="attr: { name: 'Q' + $parentContext.$index(), value: $index }, checked: $parent.CorrectAnswer" /><span></span>
Tick the correct answer
<span data-bind="text:$parent.CorrectAnswer"></span>
</label>
<a href="#" data-bind="click: $parent.remove.bind($parent)">
<i class="fa fa-times"></i>
Remove this answer
</a>
<div class="form-control" contenteditable="true" data-bind="ckeditor: $data, attr: { id: 'Q' + $parentContext.$index() + 'A' + $index() }"></div>
</div>
</div>
</div>
<!-- /ko -->
<div>CorrectAnswer: <span data-bind="text: CorrectAnswer"></span></div>
You'll notice I put a bound span on the end of the radio button label so I can see what happens to the CorrectAnswer
observable when I interact with the UI. 您会注意到,我在单选按钮标签的末尾放置了一个跨度,以便可以看到与UI交互时可观察到的
CorrectAnswer
发生了什么。 This is how I know it's correctly bound to the view model. 这就是我知道它正确绑定到视图模型的方式。 Clicking a radio button or its label changes the value of
CorrectAnswer
exactly as intended. 单击单选按钮或其标签
CorrectAnswer
完全按预期更改CorrectAnswer
的值。
This also allows me to know that CorrectAnswer contains the value I expected. 这也使我知道CorrectAnswer包含我期望的值。
Let's take a closer look at the binding in case it isn't obvious. 让我们仔细看看绑定,以防它不明显。
attr: { name: 'Q'+$parentContext.$index(), value: $index }, checked: $parent.CorrectAnswer
All the answers for a given question get the same name Qx and a value provided by the item's list position. 给定问题的所有答案都具有相同的名称Qx和该项目的列表位置提供的值。 When an item is clicked its list position is written to
CorrectAnswer
. 单击某项时,其列表位置将写入
CorrectAnswer
。 This does happen, as evidence by the new value showing up in the telltale div. 这确实发生了,这是Telltale div中显示的新值的证据。
So, what could be preventing the UI from initialising as checked when everything else is fine? 那么,在其他一切都没问题的情况下,又有什么可能阻止UI初始化呢?
It isn't an initialisation problem, it's a type compatibility problem. 这不是初始化问题,而是类型兼容性问题。 The value of a radio input is of type string.
单选输入的值是字符串类型。 The value provided by my view model is of type number.
我的视图模型提供的值是数字类型。 Knockout does a strong comparison and does not recognise a match.
淘汰赛进行了比较,无法识别比赛。
See also Radio buttons Knockoutjs 另请参见单选按钮Knockoutjs
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.