Knockout.js ko.applyBindings() 层次结构绑定
在 js 控制台中,我收到错误:
“未捕获错误:无法解析绑定。 消息:ReferenceError:new_book 未定义; 绑定值:值:new_book().name”
我做错了什么?
In js console I get the error:
"Uncaught Error: Unable to parse bindings.
Message: ReferenceError: new_book is not defined;
Bindings value: value: new_book().name"
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您使用特定元素作为第二个参数调用 ko.applyBindings 时,它将递归地绑定该元素下的所有内容。
在您的情况下,当您调用 ko.applyBindings(new AppViewModel(), document.getElementById("content")); 时,它将绑定该元素下的所有内容,其中包括“books”和“about” 。
一些选项:
确保“内容”位于其自己的元素中(而不是
books/about)
在您的 books/about 区域周围使用自定义绑定
防止“内容”绑定进入这些元素
(此处描述:
如何停止对子元素求值的knockout.js绑定< /a>)
将视图模型添加到主视图模型并使用
with
绑定您的
子
视图模型。选项 #3 是我的推荐。这是小提琴的示例: http://jsfiddle.net/rniemeyer/8dhzK/
When you call
ko.applyBindings
with a specific element as the second parameter then it will recursively bind everything under that element.In your case, when you call
ko.applyBindings(new AppViewModel(), document.getElementById("content"));
it will bind everything under that element, which includes "books" and "about".Some options:
make sure that "content" is in its own element (not an ancestor of
books/about)
use a custom binding around your books/about areas to
prevent the "content" binding from going into those elements
(described here:
How to stop knockout.js bindings evaluating on child elements)
add your view models to a main view model and use the
with
binding against your
sub
view models.Option #3 would be my recommendation. Here is a sample from your fiddle: http://jsfiddle.net/rniemeyer/8dhzK/
您会收到错误,因为此行将
整个“content”div(包括“books”和“about”等所有子 div)绑定到不具有 new_book 属性的 AppViewModel。正如 AlfeG 在评论中指出的那样,此处 是解决问题的方法。
You get an error because this line
binds the entire "content" div (including all children divs like "books" and "about") to AppViewModel that doesn't have new_book property. As AlfeG pointed out in the comment, here is how you can solve the problem.