How to stop knockout.js bindings evaluating on child elements

后端 未结 2 922
春和景丽
春和景丽 2020-12-15 06:24

Using knockout, when you call ko.applyBinding(viewModel, \"divId\") it does a recursive binding down through the children of the element you bound to (\"divId\"

相关标签:
2条回答
  • 2020-12-15 06:55

    There are several ways that you can go on this one. Typically, you would add multiple "sub" view models to a main view model and then use the with binding on the various areas with the actual view models to bind against them.

    It is possible to technically do what you are after. You can create a custom binding that tells KO that it will handle binding the children itself. It would look like:

    ko.bindingHandlers.stopBindings = {
        init: function() {
            return { controlsDescendantBindings: true };
        }  
    };
    

    When you place this on an element, then KO will ignore the children. Then, you could call ko.applyBindings on a child of this element with a different view model.

    Sample: http://jsfiddle.net/rniemeyer/tWJxh/

    Typically though, you would use multiple view models underneath a main view model using the with binding.

    0 讨论(0)
  • 2020-12-15 07:01

    One way I have done this is to create a section for the navigation (or just a ) and bind the navVM to it. Then create another section for the content and bind the contentVM to it. That way there is no conflict and its all very separated.

    <body>
        <div id="navSection">
        </div>
        <div id="contentSection">
        </div>
    </body>
    

    Then do ko.applyBinding(navVM, "navSection") and ko.applyBinding(contentVM, "contentSection")

    0 讨论(0)
提交回复
热议问题