JSFiddle - React, Tailwind, and code Playground
by Sergio Sánchez
HTML
<script src="http://knockoutjs.com/downloads/knockout-3.4.0rc.js"></script>
<script src="https://rawgit.com/rniemeyer/knockout-postbox/master/build/knockout-postbox.js"></script>
<div id="grid">
<ul data-bind="foreach: fundList">
<li> <span data-bind="text: fundName"> </span>
<input type="checkbox" data-bind="checked: isFavorite, click: $root.favorite.bind($data, id, $index())" />
</li>
</ul> <span>IsEditable </span>
<input type="checkbox" data-bind="checked: isEditable" disabled />
</div>
<div id="details">
<ul data-bind="foreach: fundList">
<li> <span data-bind="text: fundName"> </span>
<input type="checkbox" data-bind="checked: isFavorite" />
</li>
</ul> <span>editable </span>
<input type="checkbox" data-bind="checked: editable" />
</div>
JavaScript
const jsonModel = {
"funds": [{
"id": 1,
"fundName": "BTOF",
"description": "Description for BTOF",
"isFavorite": false
}, {
"id": 2,
"fundName": "BTAS",
"description": "Description for BTAS",
"isFavorite": false
}, {
"id": 3,
"fundName": "BEP",
"description": "Description for BEP",
"isFavorite": false
}]
};
function FundEntity (fund)
{
var self = this;
self.id = fund.id;
self.fundName = fund.fundName;
self.description = fund.description;
self.isFavorite = ko.observable(fund.isFavorite);
}
function GridViewModel(model) {
var self = this;
self.fundList = ko.observableArray();
model.funds.forEach(function(fund) {
self.fundList.push(new FundEntity(fund));
});
self.favorite = function (id, index) {
var newValue = {
id: id,
index: index,
isFavorite: self.fundList()[index].isFavorite()
};
ko.postbox.publish("itemChanged", newValue);
return true;
};
self.isEditable = ko.observable().subscribeTo("myEditableTopic");
}
function FundDetailViewModel(model) {
var self = this;
self.fundList = ko.observableArray();
model.funds.forEach(function(fund) {
self.fundList.push(new FundEntity(fund));
});
ko.postbox.subscribe("itemChanged", function (newValue) {
self.fundList()[newValue.index].isFavorite(newValue.isFavorite);
});
self.editable = ko.observable(false).publishOn("myEditableTopic");
}
const gridViewModel = new GridViewModel(jsonModel);
const detailsViewModel = new FundDetailViewModel(jsonModel);
ko.applyBindings(gridViewModel, $("#grid")[0]);
ko.applyBindings(detailsViewModel, $("#details")[0]);