Binding multidimensional knockoutjs observableArray

Go To StackoverFlow.com

3

I have a JSON data. I converted it to ko.observableArray. My intension is to bind it to my View.

The JSON is as follows:

    { "1" : { "asr" : "15:50", "fajr" : "03:00", "isha" : "21:31", "maghrib" : "19:02", "zuhr" : "12:21" },
      "2" : { "asr" : "15:51", "fajr" : "02:55", "isha" : "21:35", "maghrib" : "19:04", "zuhr" : "12:21" },
      "3" : { "asr" : "15:53", "fajr" : "02:51", "isha" : "21:39", "maghrib" : "19:07", "zuhr" : "12:21" },
      "4" : { "asr" : "15:54", "fajr" : "02:46", "isha" : "21:42", "maghrib" : "19:09", "zuhr" : "12:20" }
    }

This is the javascript that converts the JSON to observableArray:

    self.prayerData(jQuery.parseJSON(data));
    $.each(self.prayerData(), function (days) {
            // It works and displays the data
            console.log(days + "  -  " + this.fajr + " | " + this.asr);
        });

This is what I done to bind the data but its not working:

<!-- ko foreach:prayerData()-->
    <tr>
        <td data-bind="text: index"></td>  <!-- Display the current row -->
        <td data-bind="text: fajr"></td>
        <td data-bind="text: zuhr"></td>
        <td data-bind="text: asr"></td>
        <td data-bind="text: maghrib"></td>
        <td data-bind="text: isha"></td>
    </tr>
<!-- /ko -->

Any help to bind this kind of data in knockout.

2012-04-05 20:59
by Maxali


2

Two things that you will want to do:

1- you need to map your object to an actual array, as the bindings assume that the value of the observableArray is an actual array. This means that you would likely want to create an empty array, loop through the each property in the object and push it to the array. Then, you can add the index as a property of the item. Something like:

var mappedToArray = [];
$.each(data, function(index, item) {
    mappedToArray.push(item);
    item.index = index;
});

2- some browsers can be touchy about comments that are put between tr tags. To be safe, you would want to put your foreach binding on a tbody tag like:

<table>
    <tr>
        <th>index</th>
        <th>fajr</th>
        <th>zuhr</th>
        <th>asr</th>
        <th>maghrib</th>
        <th>isha</th>
    </tr>
    <tbody data-bind="foreach: prayerData">
        <tr>
            <td data-bind="text: index"></td>  <!-- Display the current row -->
            <td data-bind="text: fajr"></td>
            <td data-bind="text: zuhr"></td>
            <td data-bind="text: asr"></td>
            <td data-bind="text: maghrib"></td>
            <td data-bind="text: isha"></td>
        </tr>
    </tbody>
</table>

Sample here: http://jsfiddle.net/rniemeyer/utdAm/

2012-04-05 21:29
by RP Niemeyer
Thanks @RPNiemeyer, it work - Maxali 2012-04-06 00:33
Ads