Reputation: 1945
Alright I'm a little fuzzy on iterating through javascript objects still, so hopefully you guys can clear this up for me. I'm using jQuery and Knockout to spit out server data sent as JSON. Everything seems to be working great except the actual values of the array don't seem to be applying, but I DO get the table rows constructing and there are no errors, so it has to be with my Guest(data){} function. I feel like I'm probably pointing it to the key instead of the value. Take a look at my code and JSON structure and tell me what you think.
<table>
<tbody data-bind='foreach: guests'>
<tr>
<td data-bind='value: name'></td>
<td data-bind='value: email'></td>
<td data-bind='value: guests'></td>
<td data-bind='value: code'></td>
</tr>
</tbody>
</table>
<body>
</body>
<script type="text/javascript">
function Guest(data){
this.name = ko.observable(data.name);
this.email = ko.observable(data.email);
this.guests = ko.observable(data.guests);
this.code = ko.observable(data.code);
}
function guestListViewModel(){
//Data
var self = this;
self.guests = ko.observableArray([]);
$.getJSON('/php/guests_json.php', function(json) {
var mappedGuests = $.map(json, function(item) { return new Guest(item) });
console.log(mappedGuests);
self.guests(mappedGuests);
});
}
ko.applyBindings(new guestListViewModel);
</script>
Heres what the JSON looks like from the server.
[{
"id":"8",
"name":"Greg",
"email":"[email protected]",
"guests":"1",
"code":"GVTRKwRPXD2rETD10BMCWWAB",
"checked_in":"0"},
{
"id": ....
Upvotes: 2
Views: 503
Reputation: 1945
Ahh I figured it out. It had nothing to do with my JSON object which was working perfectly. You have to be careful what kind of data-bind you apply to elements. I was using an inputs 'value' binder instead of a text spans 'text' binder.
This fixed it:
<table>
<tbody data-bind='foreach: guests'>
<tr>
<td data-bind='text: name'></td>
<td data-bind='text: email'></td>
<td data-bind='text: guests'></td>
<td data-bind='text: code'></td>
</tr>
</tbody>
</table>
Upvotes: 1
Reputation: 82297
Your json returns an array of objects. Perhaps try passing in the first value of the array (the one with the objects) like this:
var mappedGuests = $.map(json[0], function(item) { return new Guest(item) });
Upvotes: 0