How to stop knockout.js bindings evaluating on child elements

橙三吉。 提交于 2019-11-27 14:39:09

问题


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"). I would like to stop this evaluation at a child node. Is there a way to do this?

the reason why...

I would like to bind the entire page to a navigation view model, this will handle basic layout and ...smile... navigation. On the various pages I would like to bind certain regions to different view models that are not properties of the navigation view model. At the moment if I do this I get "unable to parse binding" errors as the navigation view model does not have the required properties. If I could stop the binding walking down the dom, I could just bind these items separately.


回答1:


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.




回答2:


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")



来源:https://stackoverflow.com/questions/9254632/how-to-stop-knockout-js-bindings-evaluating-on-child-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!