Is it possible to make nested reusable components with knockout?

335 views
Skip to first unread message

Niclas

unread,
Feb 17, 2016, 7:10:22 AM2/17/16
to KnockoutJS
Hi,

Let's say I have a situation where I want to display a list of people and a list of cars and that I want to nest these lists inside of some reusable ui-component.

As long as all of my data is static this is not a problem:

Now lets make this a bit more realistic where my list of people and cars are in observable arrays. I can just iterate over them and display them like this:

But when I try to put these dynamic lists inside of my reusable ui-component again it breaks:

I realize this is because the binding-context inside of the ui-component tags are that not that of my outermost context anymore, but instead that of the ui-component.

In my example this can of course be fixed by prefixing my lists with $root or $parent but what if I have a more complex situation where this is in the template of another component and I cant use $root and I use multiple ui-components wrappers? $parent.$parent.$parent...? Worse, what if my component structure is recursive and I do not know how many levels up I have to go to get my data? As you can tell there are lots of edge-cases where this would not work.

Another solution is obviously to just pass my lists as params throughout the ui-components but that would make them aware of what is going to be inside them and limit their reusability, and I want to reuse my ui-components for lots of different scenarios.

Is there a solution to making actual reusable nested components in knockout? In react for example I could just use { this.props.children } to render all my "children".

Is there anything I have missed perhaps in the documentation? All examples I find only use static markup when nesting.

Thankful for any suggestions!

Regards,
Niclas

Tuan Do

unread,
Feb 22, 2016, 11:39:39 PM2/22/16
to KnockoutJS
You can pass arbitrary data to the component without the component aware of what it is or how it is used: just bind the passed in data to the data param of the template binding inside the component's template.
This would require the component's consumers to explicitly pass in the data, but can control exact what that data is.
Reply all
Reply to author
Forward
0 new messages