I get a specific JSON from a server and want to be able to add/edit/delete items in nested arrays (variant lists, variants and columns) but I can't figure out how to do that with knockout.js.
I know that I need to change the properties in that JSON object to observables and I do it with the mapping plugin like shown under "Binding" and all values has been bind correctly - but if I change a value in an input field, the model/view is not updated automatically.
Why? Am I missing something?
So are nested arrays supported native by knockout.js without the need to write own code? How can I get this JSON to a full working knockout.js view model?
I use the current available versions (knockout: v2.1.0, mapping plugin: v2.3.2).
JSON
{
"VariantList": [
{
"ColumnCount": 1,
"Variants": [
{
"Title": "One column 100%",
"Columns": [
"100 %"
]
}
]
},
{
"ColumnCount": 2,
"Variants": [
{
"Title": "Two columns 50%/50%",
"Columns": [
"50%",
"50%"
]
},
{
"Title": "Two columns 75%/25%",
"Columns": [
"75%",
"25%"
]
}
]
}
]
}
HTML
<div data-bind="foreach: VariantList">
<h2 data-bind="text: ColumnCount"></h2>
<div data-bind="foreach: Variants">
<h3 data-bind="text: Title"></h3>
<table style="width:500px">
<tr>
<!-- ko foreach: Columns -->
<th><input data-bind="value: $data"/></th>
<!-- /ko -->
</tr>
<tr>
<!-- ko foreach: Columns -->
<td data-bind="style: {width:$data}, text:$data"></td>
<!-- /ko -->
</tr>
</table>
</div>
</div>
Binding
var viewModel;
$(function(){
viewModel = ko.mapping.fromJS(myJson);
ko.applyBindings(viewModel);
});