1

For reference, here is the jsfiddle of my problem.

Overview of the problem:

I have two lists side by side in the UI but the second list is actually an array of items on the selected item in the first list. So the data structure is like this...

var VM = {
  listOfStuff: [
    {
      subItems: [{},{}]
    },
    {
      subItems: [{},{},{}]
    }
  ]
}

with the UI looking like...

<ul id="list-of-stuff">
  <li></li>
</ul>
<ul id="list-of-subitems-on-list-of-stuff">
  <li></li>
</ul>

The problem is that I use a knockout foreach binding on the 'list-of-stuff' and it works just fine, but the subitems list never shows up. There are no binding errors or any other obvious issues so I'm not sure what I'm doing wrong...

1 Answer 1

1

It's usually easiest to use the with binding to manage access to sub-objects. Here's a working fiddle.

<h1>SubItem List</h1>
<!-- ko with: currentStuff -->
    <ul id="subitem-list" data-bind="foreach: subItems">
        <li data-bind="text:number"></li>
    </ul>
<!-- /ko -->

It's important to initialize currentStuff; The with binding will not render any html if its bound value is null or undefined.

Sign up to request clarification or add additional context in comments.

2 Comments

Perfect! I didn't know the with binding was available using the comment style. Guess I should go re-visit the documentation a bit more. So is it just not possible to access them like foreach: currentStuff.subItems? Is that documented somewhere?
You can use the child property directly, but you'll lose observability on the parent property. See this fiddle: jsfiddle.net/MWve8/8. Notice two things: the currentStuff requires () in order to get the item value, which contains the subItems property. Otherwise, you're trying to find subItems property on the ko observable function, where it doesn't exist. The other thing, is that you'll need to initialize currentStuff with a subItems property - otherwise, the foreach binding can't create a dependency

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.