javascript - knockout 嵌套绑定(bind)

标签 javascript html knockout.js

我在使用 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/

相关文章:

javascript - 在 ko.observableArray 模型绑定(bind)问题中向下移动项目

javascript - 如何获取表单 onsubmit 以检查 Google Checkout 按钮的条款

javascript - Dropbox 选择按钮在 ios8 中不返回

javascript - 将 Html 从字符串解析为文档

带有正负数量的 HTML 表单编号字段

html - 全屏登录

javascript - 从 Knockout.js 的下拉列表中获取选定的值

javascript - IE10 navigator.userAgent 脚本不起作用

html - 在div中垂直居中文本?

javascript - 在 JavaScript 中通过 key 访问对象属性