JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://github.com/downloads/SteveSanderson/knockout/knockout-2.1.0.js"></script>
<script src="https://raw.github.com/SteveSanderson/knockout.mapping/master/build/output/knockout.mapping-latest.js"></script>
With template:
<table>
<tbody data-bind="template: { name: 'ThingTmpl', foreach: AllPossibleThings }">
</tbody>
</table>
<script id="ThingTmpl" type="text/html">
<tr>
<td><input type="checkbox"
data-bind="attr: {value: ID}, checked: $root.isSelected($data)" /></td>
<td><span data-bind="text: Value"></span></td>
</tr>
</script>
<br/>
Without template (check Thing1 and watch the 2&3 appear):
<table>
<tbody data-bind="foreach: AllPossibleThings">
<tr>
<td><input type="checkbox"
data-bind="checked: $root.isSelected($data),
attr: {value: ID}" /></td>
<td><span data-bind="text: Value"></span></td>
</tr>
</tbody>
</table>
<br/>
What should be selected::
<div data-bind="text: selectedThings"></div>
JavaScript
viewModel = function (obj) {
this.selectedThings = ko.observableArray(["2","3"]);
this.AllPossibleThings = ko.observableArray(
[
{ ID: "1", Value: 'Thing1' },
{ ID: "2", Value: 'Thing2' },
{ ID: "3", Value: 'Thing3' },
{ ID: "4", Value: 'Thing4' }
]);
this.isSelected = function (thing) {
return ko.computed({
read: function () {
return this.selectedThings.indexOf(thing.ID) !== -1;
},
write: function (newValue) {
var index = this.selectedThings.indexOf(thing.ID);
if (newValue) {
// checked
if (index === -1)
this.selectedThings.push(thing.ID);
} else {
// unchecked
if (index !== -1)
this.selectedThings.remove(thing.ID);
}
}
}, this);
};
};
$(ko.applyBindings(new viewModel()));