How to pre-select an option in a dropdown knockout

2019-02-14 18:20发布

问题:

I've looked at this other question, but can't get my select box to work correctly: Binding initial/default value of dropdown (select) list

I've got the following Game object:

function Game(visitingTeamDetails, homeTeamDetails, game) {
if (arguments.length > 0) {
    this.VisitingTeamDetails = visitingTeamDetails;

    this.HomeTeamDetails = homeTeamDetails;

    this.GameId = ko.observable(game.GameId);
    this.HomeTeamName = ko.observable(game.HomeTeamName);
    this.VisitingTeamName = ko.observable(game.VisitingTeamName);
    this.SportTypeName = ko.observable(game.SportTypeName);
    this.HomeAccountName = ko.observable(game.HomeAccountName);
    this.VisitingAccountName = ko.observable(game.VisitingAccountName);
    this.GameDateString = ko.observable(game.GameDateString);
    this.GameTimeString = ko.observable(game.GameTimeString);
    this.AvailableSportTypes = ko.observableArray(game.Sports);

    this.sportTypeFunction = function () {
        for (sportType in this.AvailableSportTypes()) {
            if (this.AvailableSportTypes()[sportType].Name == this.SportTypeName()) {
                return this.AvailableSportTypes()[sportType];
            }
        }
        return null;
    };

    this.SportType = ko.observable(game.SportType);
}
}

SportType is an object with Name and SportTypeId.

I have the following template:

 <td rowspan="3"><select data-bind="options: AvailableSportTypes, value: SportType, optionsText:'Name', optionsCaption: 'Choose...'" class="sportType"></select></td>

AvailableSportTypes is a list of SportType.

The list is coming in with the names of the SportTypes in the drop down list, but I can't make the initial selection be SportType. I wrote sportTypeFunction to show myself that the data was coming in correctly, and it would select the correct value, but changing my selection in the drop down would not update SportType.

I'm sure I'm doing something wrong. Anyone see it?

Thanks

回答1:

When game.SportType gets passed in, it needs to be a reference to the an item in the game.AvailableSportTypes and not just an object that looks the same.

Basically two objects are not equal unless they are actually a reference to the same object.

var a = { name: "test" },
    b = { name: "test" }; 

    alert(a === b); //false

So, you would need to call your function to locate the correct object in the array and set it as the value of your observable.

Not that it is way better, but in KO 1.3 you can extend .fn of observables, observableArrays, and dependentObservables to add additional functionality.

Here is a sample: http://jsfiddle.net/rniemeyer/ZP79w