Two view models ,one for the whole page & the othe

2019-06-01 19:12发布

I am aware that ko.applyBindings can take a second parameter which is the DOM element that it will bind to

but my case is different i have a big page i want to specify a viewmodel for it by using ko.applyBindings(bigModel)

and then there is a small sidebar section which is in the middle of the page i want to specify another view model for it by using ko.applyBindings(smallModel, $("#sidebar")[0])

when i use bounded attributes using knockout in the small #sidebar section it throws an error Unable to parse bindings yet it still bind the values (Ex. <span 'text:propertyOnSmallModel' />) i after that tried to add these attributes as empty attributes on the bigModel , it didnt throw.

How can i apply this , use two view models one for the whole page and the other for a specific section

标签: knockout.js
2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-06-01 19:53

You can tell Knockout.js to stop binding using this handler:

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

ko.virtualElements.allowedBindings.stopBinding = true;

Then using:

        <!-- ko stopBinding: true -->
        <!-- /ko -->

html comments in your web page to stop binding.

So, you bind the bigger model to the whole page, use the above html comments to stop that model being bound on your specific section.

查看更多
叛逆
3楼-- · 2019-06-01 20:10

I don't see any problem with having child viewmodels. Add your sidebar viewmodel as a property of the parent viewmodel. Use the 'with' binding to bind the child viewmodel to your sidebar element.

查看更多
登录 后发表回答