Array mapping issue
Example of using mapping to add observable to an array element
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<table class="table">
<thead>
<tr>
<th>Product</th>
<th>Line Value</th>
<th>Cost</th>
<th>Qty</th>
</tr>
</thead>
<tbody data-bind="foreach: Lines">
<tr>
<td><span data-bind="text: ProductCode"></span></td>
<td><span data-bind="text: LineValue"></span></td>
<td><span data-bind="text: Cost"></span></td>
<td>
<input type="text" data-bind="value: Qty" />
</td>
</tr>
</tbody>
</table>
CSS
/* Latest compiled and minified CSS included as External Resource*/
/* Optional theme */
@import url('//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-theme.min.css');
body {
margin: 10px;
}
JavaScript
var order = {
Id: 1,
CustomerName: 'A Customer',
Lines: [{
ProductCode: 'Prod_1',
Cost: 11.11,
Qty: 1
}, {
ProductCode: 'Prod_2',
Cost: 22.22,
Qty: 2
}, {
ProductCode: 'Prod_3',
Cost: 33.33,
Qty: 3
}, ]
};
var orderMapping = {
'Lines': {
create: function(options) {
return new orderLineViewModel(options.data);
}
}
}
var orderLineViewModel = function(data) {
var self = this;
if (data != null) {
ko.mapping.fromJS(data, {}, this);
}
self.LineValue = ko.computed(function() {
return (self.Cost() * self.Qty()).toFixed(2);
});
};
var orderViewModel = function(data) {
var self = this;
ko.mapping.fromJS(data, orderMapping, this);
};
var viewModel = new orderViewModel(order);
ko.applyBindings(viewModel);