There have been a lot of questions posted about using checkboxes in a foreach loop in Knockout, but I haven't seen an answer to why initalizing the checked binding works in some situations and not others.
With this simple viewmodel:
viewModel = function (obj) {
this.AllPossibleThings = ko.observableArray(
[
{ ID: "1", Value: 'Thing1' },
{ ID: "2", Value: 'Thing2' },
{ ID: "3", Value: 'Thing3' },
{ ID: "4", Value: 'Thing4' }
]);
this.selectedThings = ko.observableArray(["2","3"]);
};
$(ko.applyBindings(new viewModel()));
Putting these in a foreach template works as you'd expect. It shows 4 checkboxes, with 2 and 3 pre-checked:
<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.selectedThings" /></td>
<td><span data-bind="text: Value"></span></td>
</tr>
</script>
Doing what should be the equivalent without a template doesn't work the same:
<table>
<tbody data-bind="foreach: AllPossibleThings">
<tr>
<td><input type="checkbox"
data-bind="checked: $root.selectedThings,
attr: {value: ID}" /></td>
<td><span data-bind="text: Value"></span></td>
</tr>
</tbody>
</table>
The non-template one shows 4 checkboxes, but with none pre-checked. BUT, when you click, say, the 1st checkbox then 2 and 3 get checked. It's like it got bound before the "selectedThings" array got created and the change was never observed.
Fiddle to demonstrate with both: http://jsfiddle.net/jturnage/j763w/
Anybody know why the template foreach works here, but the regular foreach binding does not?