I'm experiencing a strange problem with Knockout's mapping plug-in.
If I fill an observable array through mapping I can't iterate the array or get its length, even though the UI is updated correctly, the array seems empty.
You can find a working jsFiddle here: http://jsfiddle.net/VsbsC/
This is the HTML mark-up:
<p><input data-bind="click: load" type="button" value="Load" /></p>
<p><input data-bind="click: check" type="button" value="Check" /></p>
<table>
<tbody data-bind="foreach: items">
<tr>
<td data-bind="text: name"></td>
<td data-bind="text: value"></td>
</tr>
</tbody>
</table>
<p data-bind="text: total"></p>
This is the JavaScript code:
var ViewModel = function () {
var self = this;
self.items = ko.observableArray();
self.load = function () {
self.items([
{ "name": "joey", "value": 1 },
{ "name": "anne", "value": 2 },
{ "name": "paul", "value": 3 },
{ "name": "mike", "value": 4 }
]);
};
self.check = function () {
alert(self.items().length);
};
self.total = ko.computed(function () {
var total = 0;
for (var i = 0; i < self.items().length; i++) {
total += self.items()[i].value;
}
return total;
});
};
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
When I click on the Load button both the records and the total are displayed correctly, and when I click the Check button I get the correct item number.
However, if I change
self.items([
{ "name": "joey", "value": 1 },
{ "name": "anne", "value": 2 },
{ "name": "paul", "value": 3 },
{ "name": "mike", "value": 4 }
]);
to
self.items(ko.mapping.fromJS([
{ "name": "joey", "value": 1 },
{ "name": "anne", "value": 2 },
{ "name": "paul", "value": 3 },
{ "name": "mike", "value": 4 }
]));
the UI still get rendered correctly, but the total shows zero, clicking Check yields zero too, and console.info-ing self.items yields an empty array.
How is this possible? I've re-read the tutorials countless times, and I can't understand what I'm doing wrong.
P.s. I need to fill the observable array through the mapping plug-in because in the real page the values are coming from an AJAX request.