Knockout.js ko.applyBindings() hierarchy binding

回眸只為那壹抹淺笑 提交于 2019-12-24 11:36:18

问题


http://jsfiddle.net/3JRVS/1/

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?


回答1:


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:

  1. make sure that "content" is in its own element (not an ancestor of books/about)

  2. 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)

  3. 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/




回答2:


You get an error because this line

ko.applyBindings(new AppViewModel(), document.getElementById("content"));

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.



来源:https://stackoverflow.com/questions/9256938/knockout-js-ko-applybindings-hierarchy-binding

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!