Binding multidimensional knockouts of an observable array

I have JSON data. I converted it to ko.observableArray. My intention is to tie it to my view.

JSON looks like this:

    { "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 an observable array:

    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 did for data binding, but doesn't work:

<!-- 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 for tying this type of data to knockout.

+3


source to share


1 answer


Two things you want to do:

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

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

      



2- some browsers can be touching about comments that are placed between tags tr

. To be safe, you need to bind an anchor foreach

to a tag tbody

, for example:

<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>

      

An example is here: http://jsfiddle.net/rniemeyer/utdAm/

+2


source







All Articles