Etienne Noël
Etienne Noël

Reputation: 6166

knockout.js - 2d array binding problems

I want to create a 2d array binding using knockout.js

I want it to generate data based on the content of this 2d array but it does not work.

First, here's my knockout model

self.searchResults = ko.observableArray()

//Let's populate some data so you know the structure of my array
self.searchResults = new Array("Network", "Devices")

self.searchResults["Network"] = new Array("1", "2");
self.searchResults["Devices"] = new Array("a", "b", "c");

Now, I have this in my html code:

<ul data-bind="foreach: searchResults">
     <li data-bind="text:$data"></li>
     <ul data-bind="foreach: $data">
        <li data-bind="text: $data"></li>
     </ul>
</ul>

Here the expected result I'm hoping for:

<ul>
    <li>Network</li>
    <ul>
       <li>1</li>
       <li>2</li>
    </ul>
    <li>Devices</li>
    <ul>
       <li>a</li>
       <li>b</li>
       <li>c</li>
    </ul>
</ul>

The problem is that it loops through the letters to show them. Here's the jsFiddle example to demonstrate: http://jsfiddle.net/MMrpM/1/

Upvotes: 1

Views: 3312

Answers (1)

GotDibbs
GotDibbs

Reputation: 3167

Your problem is partly that you're setting your knockout observable incorrectly. In knockout you need to invoke your observable to get or set the value as such:

// Get
var val = self.searchResults();

// Set
self.searchResults(val);

As well, JavaScript does not allow you to create and manipulate arrays as you have. You need to actually create an array of objects. Therefore your code should in fact be similar to:

self.searchResults = ko.observableArray();

//Let's populate some data so you know the structure of my array
self.searchResults = [ { name: "Network", children: [] }, { name: "Devices", children: [] } ]

self.searchResults[0].children = ["1", "2"];
self.searchResults[1].children = ["a", "b", "c"];

See it working in this jsfiddle: http://jsfiddle.net/dkqdw/

Upvotes: 4

Related Questions