所以这就是我想做的
使用 knock out 我想要一些只在变量 myvalue 有一些内容时出现
这是我的代码
html
<script type='text/javascript' src="../js/knockout-2.3.0.js" defer="defer"></script>
<script type="text/javascript" src="../js/searchModel.js" defer="defer" ></script>
<h2>Welcome to My World :D</h2>
<div data-bind="visible: myValues().length > 0">
You will see this message only when 'myValues' has at least one member.
</div>
JS
function helloModel() {
// Editable data
this.viewModel = {
myValues: ko.observableArray([]) // Initially empty, so message hidden
};
//viewModel.myValues.push("some value"); // Now visible
}
我总是得到的错误是:
Uncaught ReferenceError: Unable to parse bindings.
Bindings value: visible: myValues().length > 0
Message: myValues is not defined
很可能是因为我在脚本标签中添加了 defer 属性,这意味着在我渲染整个 html 元素之前不会加载文件
然而这很重要,我将在以下三种情况下进行解释:
1- 延迟挖空而不是搜索模型如下
所以现在搜索模型将在渲染 HTML 元素之前包含在内。 但是这会导致问题,因为它使用了 knokout 的代码
Uncaught ReferenceError: ko is not defined
2-Defer for search model not knokout
<script type='text/javascript' src="../js/knockout-2.3.0.js" defer="defer"></script>
<script type="text/javascript" src="../js/searchModel.js" ></script>
会导致同样的老问题
Uncaught ReferenceError: Unable to parse bindings.
Bindings value: visible: myValues().length > 0
Message: myValues is not defined
3- 忘记延迟
<script type='text/javascript' src="../js/knockout-2.3.0.js" ></script>
<script type="text/javascript" src="../js/searchModel.js" ></script>
也会导致后续问题 未捕获的类型错误:无法读取 null 的属性“nodeType”
因为脚本会在 html 上加载并尝试在元素创建之前绑定(bind)它
那么您有什么建议来解决这个问题:)
最佳答案
这应该适用于您发布的代码。
<h2>Welcome to My World :D</h2>
<div data-bind="visible: myValues().length > 0">
You will see this message only when 'myValues' has at least one member.
</div>
<script type='text/javascript'>
ko.applyBindings((new helloModel()).viewModel)
</script>
我建议将您的 View 模型重构为如下所示
function helloModel() {
var self = this;
self.myValues = ko.observableArray([]);
self.pushHello = function(data,e) {
self.myValues.push("Hello, world!");
};
//self.myValues.push("some value"); // Now visible
}
然后在你的初始化代码中
<script type='text/javascript'>
ko.applyBindings(new helloModel())
</script>
关于javascript - Uncaught ReferenceError : Unable to parse bindings,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18019797/