JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://raw.github.com/SteveSanderson/knockout.mapping/master/build/output/knockout.mapping-latest.js"></script>
<h3>First VM:</h3>
<p><b>Title:</b> <span data-bind="text: first.title"></span></p>
<p><b>Children:</b></p>
<ul>
<!-- ko foreach: first.children -->
<li><span data-bind="text: name"></span> ( id:<span data-bind="text: id"></span>)</li>
<!-- /ko -->
</ul>
<p><b>Just first.children().length:</b> <span data-bind="text: first.children().length"></span></p>
<p><b>Computed children length:</b></p>
<p data-bind="html: first.calLength"></p>
<p data-bind="html: first.getWarning"></p>
<p>----------------------------------</p>
<h3>Second VM:</h3>
<p><b>Title:</b> <span data-bind="text: second.title"></span></p>
<p> </p>
<p><button data-bind="click: first.updateData" style="cursor: pointer">update data</button></p>
JavaScript
var data = {
'firstObj' : {
'title' : 'CURRENT title goes here',
'children' : [
{ 'id': '00001', 'name': 'Rube no 1' },
{ 'id': '00002', 'name': 'Rube no 2' },
{ 'id': '00003', 'name': 'Rube no 3' }
],
'warning' : false
},
'secondObj' : {
'title' : 'Second Item title'
}
},
updateEverything = function() {
data = {
'firstObj' : {
'title' : 'UPDATED TITLE goes here',
'children' : [
{ 'id': '00004', 'name': 'Rube no 4' },
{ 'id': '00005', 'name': 'Rube no 5' },
{ 'id': '00006', 'name': 'Rube no 6' },
{ 'id': '00007', 'name': 'Rube no 7' },
{ 'id': '00008', 'name': 'Rube no 8' },
{ 'id': '00009', 'name': 'Rube no 9' }
],
'warning' : true
},
'secondObj' : {
'title' : '2nd Title UPDATED'
}
};
ko.mapping.fromJS(data.firstObj, viewModel.first);
ko.mapping.fromJS(data.secondObj, viewModel.second);
// console.log('this is update Training function from main.js');
},
firstVM = function() {
var self = this,
item = null;
item = data.firstObj;
self.title = ko.observable(item.title);
self.updateData = function() {
updateEverything();
return false;
};
self.children = ko.observableArray(item.children);
self.calLength = ko.computed(function() {
return 'Total <span style="font-size: 11px;">(self.children().length)</span>: ' + self.children().length;
});
self.warning = ko.observable(item.warning);
self.getWarning = ko.computed(function() {
if (self.warning()) {
return '<span style="color: #f00">Why self.children().length in VM function is not updated?</span>';
}
});
},
secondVM = function() {
var self = this,
item = null;
item = data.secondObj;
self.title = ko.observable(item.title);
},
viewModelObj = {
first : new firstVM(),
second : new secondVM()
},
mappingOptions = {
'first' : {
create : function(options) {
return ko.mapping.fromJS(options.data, {},...