我在使用 knockout 和表单以及在不引发错误的情况下应用绑定(bind)时遇到问题。
我想将表单的逻辑拆分为多个 View 模型,但当我尝试绑定(bind) foobar 时,我遇到了 bar 和 foos 中的绑定(bind)错误,但未找到
我尝试在下面的示例中显示这一点。
有没有办法实现所需的行为?有没有办法说组合三个 View 模型中的所有绑定(bind)然后将它们分配给 foobar?
bars_observable 是在 barViewModel 的构造函数中创建的 ko.observable。
<div id="foobar">
<form data-bind="with: newFooBar, submit: submitFooBar">
<section id="bars">
<div data-bind="text: bars_observable"></div>
</section>
<section id="foos">
foo stuff
</section>
</form>
</div>
<script type="text/javascript">
$(function () {
var foobarViewModel, fooViewModel, barViewModel;
foobarViewModel = new ViewModels.FoobarViewModel({
fooViewModel: new ViewModels.FooViewModel({}),
barViewModel: new ViewModels.BarViewModel({})
});
ko.applyBindings(foobarViewModel, document.getElementById("foobar"));
});
</script>
错误是
"Uncaught Error: Unable to parse bindings. Message: ReferenceError: bars_observable is not defined;"
最佳答案
我建议将 fooViewModel 和 barViewModel 对象放入 FoobarViewModel 中。在这种情况下,您只需调用 ko.applyBindings 一次。
<div id="foobar">
<form data-bind="with: newFooBar, submit: submitFooBar">
<section id="bars" data-bind="with: barViewModel">
<div data-bind="text: bars_observable"></div>
</section>
<section id="foos" data-bind="with: forViewModel">
foo stuff
</section>
</form>
</div>
<script type="text/javascript">
$(function () {
var foobarViewModel = new ViewModels.FoobarViewModel({});
ko.applyBindings(foobarViewModel, document.getElementById("foobar"));
});
function ViewModels.FoobarViewModel() {
var self = this;
self.fooViewModel = new ViewModels.FooViewModel({});
self.barViewModel = new ViewModels.BarViewModel({});
...
}
</script>
关于javascript - knockout 嵌套绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11689607/