问题
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:
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
withbinding against yoursubview 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