Jeya Suriya Muthumari
Jeya Suriya Muthumari

Reputation: 2021

Knockout Js: foreachBinding

I have object models which is of format below,

models:
   [
      0: {
         [functions]: ,
         __proto__: { },
         Main: "Sample",
         sub: [
            0: " Sub1",
            1: " Sub2",
            2: " sub3",
            3: " sub4",
            4: " sub5",
            5: " sub6",
            6: " sub7",
            7: " sub8",
            length: 8
         ]
      },
      1: { },
      2: { },

I have listed first three elements of the object as sample. Also first element is elaborated. I am trying to list this as below.

Main 1
 sub details
Main 2
 sub details

I have tried like, I could not figure out why my data binding is not working. Following code not displaying anything in the screen.

            <td>
                <ul class="tree">
                    <li data-bind="foreach: models" >
                        <span data-bind="text: $data[$index].main"></span>
                        <ul data-bind="foreach: subDetails in models.sub">
                            <li><span data-bind="text: $data[$index].sub"></span></li>
                        </ul>
                    </li>
                </ul>
            </td>

Please check my fiddle here. Any help would be appreciated.

Upvotes: 0

Views: 59

Answers (1)

gkb
gkb

Reputation: 1459

There are a lot of issues with your fiddle. Here is a list -

  • You have written ko.applybindigs which should have been ko.applyBindings

  • The model should be a part of your viewModel, so you will need to attach that variable to your viewModel. Like var self = this; self.model = [].... Declaring it just as a private var will not expose it to the knockout bindings and hence that will not work.

  • Once inside of a foreach binding, you don't need $index to access the objects inside of the array, just accessing them by their names is all you need. So <span data-bind="text: $data[$index].Main"></span> is replaced by <span data-bind="text: Main"></span>

  • You have another foreach nested inside the outer one, there too you have used $index accessor which really isn't necessary. To add to that <ul data-bind="foreach: subdetails in model.sub"> can easily be replaced with <ul data-bind="foreach: Sub"> (please also notice the typo in sub which should have been Sub)

Corrected fiddle here

Upvotes: 1

Related Questions