[英]Knockout.js is returning an undefined event for the focus binding in Internet Explorer
[英]undefined binding in knockout.js
作为开发JS应用程序的初学者,目前,我仅限于观察现有代码并尝试在摆弄变量名的同时重现代码(这样我便可以了解自己是否理解正确)。
这就是我用KO.js编写的JS测验代码所做的...这是“我的”版本(根本没有太多更改...)
我的问题是,当我尝试运行代码时,不是在脚本中而是在KO库中得到“ isCorrect is undefined”。 当我注释HTML中包含isCorrect的行时,我仍然在KO库中得到“ correctNbrAnswers is undefined”的信息。
就像KO不理解我在引用适当的模板时使用的数据参数...
<script id="questionView" type="text/html">
<div>Question <span data-bind="text: index"></span></div>
<div data-bind="visible: selectedAnswer() === undefined">
<div data-bind="text: questionText"></div>
<ul data-bind="template: { name: 'answerView', foreach: answers }"></ul>
</div>
<div data-bind="visible: selectedAnswer() !== undefined">
<div data-bind="template: { name: 'questionResultView', data: selectedAnswer }"></div> <!-- isCorrect id defined for answers, so if KO respects this scope, this should work... But it doesn't! -->
<a href="#" data-bind="click: $parent.nextQuestion">Next</a>
</div>
</script>
<script id="questionResultView" type="text/html">
<div data-bind="visible: isCorrect">Bonne réponse !</div> <!-- Returns isCorrect is undefined (knockout.js line blablabla) -->
<div data-bind="visible: !isCorrect">Non. La bonne réponse était <span data-bind="text: $parent.correctAnswer.answerText"></span></div>
</script>
如果有人可以阐明这件事,我会喜欢的。
谢谢!
阿里; o)
问题是selectedAnswer
可能undefined
也可能undefined
。 通常没关系,但是您认为逻辑有点缺陷。
<script id="questionView" type="text/html">
<div data-bind="visible: selectedAnswer() === undefined">
<!-- _visible_ if selectedAnswer is undefined -->
</div>
<div data-bind="visible: selectedAnswer() !== undefined">
<!-- _not visible_ if selectedAnswer is undefined -->
<div data-bind="template: { name: 'questionResultView', data: selectedAnswer }"></div>
</div>
</script>
注意我添加的评论。
当selectedAnswer
undefined
时,第一个div
可见 。 表示仍会评估div
的主体,只有结果不可见。
当selectedAnswer
undefined
时,第二个div
不可见 。 身体仍在评估中。 由于模板使用selectedAnswer
,因此它试图呈现undefined
对象。 当selectedAnswer
undefined
时,您需要防止第二个div
的主体被求值。
您可以通过多种方法来完成此操作,但我们会坚持最简单的方法。
将第二个div
上的visible
绑定更改为if
绑定。 有关更多信息,请参考文档 。 基本上,这与visible
绑定非常相似,不同之处在于,如果条件不符合我们的要求,它不评估主体。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.