How to pre-select a parameter in the js knockout

I looked at this other question, but I can’t get my select box to work correctly: Linking the start / default value of a drop-down list (select)

I have 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 SportType list.

The list includes a list of SportTypes names in the drop-down list, but I cannot make the initial SportType selection. I wrote sportTypeFunction to show that the data is coming in correctly and it will select the correct value, but changing my selection from the drop-down list will not update SportType.

I am sure that I am doing something wrong. Does anyone see this?

thanks

+4
source share
1 answer

When game.SportType is passed, it should be a reference to an element in game.AvailableSportTypes , not just an object that looks the same.

In principle, two objects are not equal if they are not actually a reference to the same object.

 var a = { name: "test" }, b = { name: "test" }; alert(a === b); //false 

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

Not that this is better, but in KO 1.3 you can extend the .fn observable, observable attributes and dependObservables to add extra features.

Here is an example: http://jsfiddle.net/rniemeyer/ZP79w

+11
source

Source: https://habr.com/ru/post/1385580/


All Articles