Knockout problem when changing moption lists
HTML
<script src="http://knockoutjs.com/downloads/knockout-3.2.0.js"></script>
<label>Some header field</label>
<input type="text" id="txtSomeHeaderField" data-bind="value: HeaderField" />
<fieldset>
<legend>Active Child Record</legend>
<label>Category</label>
<select id="ddlCategory" data-bind="options: categories, value: ActiveChildRecord().Category, valueAllowUnset: true, optionsCaption:'Select category...'" ></select>
<label>Things</label>
<select multiple id="ddlThings" data-bind="options: ThingsList, value: ActiveChildRecord().Favorite, valueAllowUnset: true, optionsCaption:'Select favorite thing...'" ></select>
</fieldset>
<button data-bind="click: AddChildRecord" >Add a child record</button>
<table id="tblChildRecords" border>
<thead>
<tr>
<th>Category</th>
<th>Favorite Thing</th>
</tr>
</thead>
<tbody data-bind="foreach: ChildRecords">
<tr data-bind="click: ChildRecordClicked, css: {activeRow: ActiveChildRecord() === $data}" >
<td data-bind="text: Category() || '-'"></td>
<td data-bind="text: Favorite() || '-'"></td>
</tr>
</tbody>
</table>
<p>Steps to reproduce problem:</p>
<ol>
<li>Click "Add child record"</li>
<li>Click on that row to make it the "active" record</li>
<li>Choose category "Pets" and thing "Dog"</li>
<li>Click "Add child record"</li>
<li>Click on the new row to make it the "active" record</li>
<li>Choose category "Colours" and thing "Blue"</li>
<li>Now click back on the first row... <strong>"Dog" disappears!</strong></li>
</ol>
CSS
.activeRow { background-color: #CCFFCC; }
JavaScript
var categories = ["Pets", "Colours", "Foods"];
var MyViewModel = function(){
var _this = this;
this.HeaderField = ko.observable("this value is unimportant");
this.ChildRecords = ko.observableArray([]);
this.ActiveChildRecord = ko.observable({ Category: ko.observable(), Favorite: ko.observable()});
this.ThingsList = ko.observableArray();
this.AddChildRecord = function(){
_this.ChildRecords.push({ Category: ko.observable(), Favorite: ko.observable()});
}
this.ChildRecordClicked = function(childRecord){
_this.ActiveChildRecord(childRecord);
}
this.RefreshThingsList = ko.computed(function(){
var strActiveCategory = _this.ActiveChildRecord().Category();
switch(strActiveCategory){
case "Pets": _this.ThingsList(["Dog", "Cat", "Fish"]); break;
case "Colours": _this.ThingsList(["Red", "Green", "Blue", "Orange"]); break;
case "Foods": _this.ThingsList(["Apple", "Orange", "Strawberry"]); break;
}
});
}
ko.applyBindings(MyViewModel);