Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 652
Bodzio Avatar asked Jun 04 '26 18:06

Bodzio


1 Answers

One more option is to use the future let binding which will be coming out with in a later iteration of knockout. This would allow you to do the following in the grandparent component:

<!-- ko let: { $parentComponent: $component } -->
<parent-component params="variable: $component.someVariable">
    <child-component params="variable: $parentComponent.someVariable"></child-component>
</parent-component>
<!-- /ko -->

Basically allowing you to get access to a parent component from another component.

The let binding code can be found here: https://github.com/knockout/knockout/blob/241c26ca82e6e4b3eaee39e3dc0a92f85bc1df0c/src/binding/defaultBindings/let.js

like image 192
k2snowman69 Avatar answered Jun 06 '26 09:06

k2snowman69