Bodzio Bodzio - 1 month ago 26
Javascript Question

Communication between nested components in Knockout.js

I'm trying to use knockout custom elements in my application, but I'm stuck with one problem. I have two nested custom elements and I want them to communicate. I tried to share observable between them, but I'm constantly getting an error:

Unable to process binding "template: function (){return { nodes:$componentTemplateNodes} } Message: someVariable is not defined
- inner component can't access observable. How to fix this? Or maybe there is a better way to communicate between nested components? I'm using knockout 3.3.0

my code:

html:

<parent-component params="variable: someVariable">
<child-component params="variable: someVariable"></child-component>
</parent-component>


js:

ko.components.register("parent-component", {
viewModel: function (params) {
this.params = params;
},
template: "<div data-bind='text: params.variable'></div> <!-- ko template: { nodes: $componentTemplateNodes } --><!-- /ko -->"
});

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

ko.applyBindings({
someVariable: ko.observable(true)
});


demo: http://jsfiddle.net/50zbtxe3/

TSV TSV
Answer

The thing is that "someVariable" does not exist inside the "parent-component". You should pass it to the next binding level:

ko.components.register("parent-component", {
viewModel: function (params) {
    this.params = params;
    this.someVariable = params.variable;
},
template: "<div data-bind='text: params.variable'></div> <!-- ko template: { nodes: $componentTemplateNodes } --><!-- /ko -->"
});

I've updated the jsfiddle: http://jsfiddle.net/50zbtxe3/1/