2

我在使用敲除和表单并在不引发错误的情况下应用绑定时遇到问题。

我想将表单的逻辑拆分为几个视图模型,但是当我尝试绑定 foobar 时,我遇到了 bar 中的绑定错误和 foos 未找到

我试图在下面的示例中显示这一点。

有没有办法实现所需的行为?有没有办法说组合来自三个视图模型的所有绑定,然后将它们分配给 foobar?

bar_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;"
4

2 回答 2

1

我建议将 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>
于 2012-07-27T14:24:50.223 回答
1

If you are writing a modular system, creating a top level view model may not be possible. In knockout 2.0 you can tell knockout to stop parsing bindings at a certain point. Then you can call applyBindings again for the container. Here is an article which explains how to do it.

http://www.knockmeout.net/2012/05/quick-tip-skip-binding.html

于 2013-12-13T09:01:57.933 回答