jquery - Knockout- How to check if item in the loop exist while binding -
i've below html bind array foreach data binding.
<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 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>
this how prepare view model bind above html-
var datafromserver = { "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" } }; var viewmodel = function(data) { //map data array var mappedtoarray = []; $.each(data, function(index, item) { mappedtoarray.push(item); item.index = index; }); this.prayerdata = ko.observablearray(mappedtoarray); }; ko.applybindings(new viewmodel(datafromserver));
before binding of item in foreach binding, first want check whether item in array exist of not. below-
for example if datafromserver[0] below missing "asr" , "fajr" while binding give error.
"1": { "isha": "21:31", "maghrib": "19:02", "zuhr": "12:21"
},
jsfiddle same is
if of items not have properties can use $data
property inside foreach
safely access them.
in case if property missing binding still work won't display anything:
<tbody data-bind="foreach: prayerdata"> <tr> <td data-bind="text: index"></td> <!-- display current row --> <td data-bind="text: $data.fajr"></td> <td data-bind="text: $data.zuhr"></td> <td data-bind="text: $data.asr"></td> <td data-bind="text: $data.maghrib"></td> <td data-bind="text: $data.isha"></td> </tr> </tbody>
demo jsfiddle.
you can provide default values in binding if property missing with:
<td data-bind="text: $data.fajr || 'no fajr property'"></td>
demo jsfiddle
Comments
Post a Comment