I have seen some solutions elsewhere for this problem, but have not yet found how to make this work in my specific circumstances.
An observableArray populates an html list. Inside the list, a user can edit one of the values for a particular row. The item to be edited in the row is itself an observableArray that populates a dropdown list. The array for the drop down list is populated via an ajax call when an edit button on the row is clicked (edit button not shown in code below).
I have this all working fine, except for one important issue: as of yet, the value in the dropdown list is not being pre-populated.
Below is a gross mockup of what the real code is doing.
If I call selectedTeamType as selectedTeamType() in the html, then the intial value is populated, but further changes to the select box are not registered. If I call selectedTeamType as just selectedTeamType, then the intial value is not set properly, but further changes to the select box are registered.
HTML
<table>
<tr> <!-- ko foreach: my.TeamViewModel.Teams -->
<td data-bind="text: TeamID"></td>
<td data-bind="text: TeamText"></td>
<td> <!-- the TeamType will be editable, so we provide a dropdown list, but default to the current value -->
<select data-bind="options: my.TeamViewModel.TeamTypes,
optionsText: 'TeamTypeText',
optionsValue: 'TeamTypeID',
value: selectedTeamType"></select>
</td>
</tr> <!-- /ko -->
</table>
JAVASCRIPT
var my = my || {};
$(function () {
my.TeamModel = function () {
var self = this;
self.TeamID = ko.observable();
self.TeamText = ko.observable();
self.TeamTypeID = ko.observable();
self.selectedTeam = ko.observable();
self.Edit = function () {
my.TeamViewModel.load_TeamTypes();
};
};
my.TeamTypesModel = function () {
var self = this;
self.TeamTypeID = ko.observable();
self.TeamTypeText = ko.observable();
};
my.TeamViewModel = function () {
var Teams = ko.observableArray([]),
TeamTypes = ko.observableArray([]),
load_TeamTypes = function () {
$.ajax({
// only part of ajax call displayed here for sake of brevity...
$.each(data, function (i, d) {
TeamTypes.push(new my.TeamTypesModel()
.TeamTypeID(d.TeamTypeID)
.TeamTypeText(d.TeamTypeText)
);
});
});
},
load_Teams = function () {
$.ajax({
// only part of ajax call displayed here for sake of brevity...
$.each(data, function (i, d) {
Teams.push(new my.TeamModel()
.TeamID(d.TeamID)
.TeamText(d.TeamText)
);
});
}
});
};
return {
Teams: Teams,
TeamTypes: TeamTypes,
load_TeamTypes: load_TeamTypes
};
} ();
my.TeamViewModel.load_Teams();
ko.applyBindings(my.TeamViewModel);
});