Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing the $root binding context within a knockout.js component template

Tags:

knockout.js

Accessing the $root binding context in the template of a KO component returns the view model of the page instead of the component's view model. Why is this and how can I access the component's view model from within a nested binding context without using $parent?

The following example snippets output "test2".

HTML:

<my-component></my-component>

JS:

ko.components.register("my-component", {
    template: "<div data-bind='text: $root.test'></div>",
    viewModel: function(params) { this.test = "test1" }
});

ko.applyBindings({ test: "test2" });
like image 886
ctusch Avatar asked Feb 05 '26 20:02

ctusch


1 Answers

Currently you cant use $root binding context as component context, but $parent and $parents[] are working as expected see documentation. There will be $component binding context same as $root for page in version 3.3 and it is allready done github.

like image 166
Dmitriy Krupin Avatar answered Feb 09 '26 09:02

Dmitriy Krupin