0
votes

Hi i have a application which data is passed from one page to another with predefined data objects/arrays assigned to it, my issue is i can see the observableArray having a value and then it turns the SelectedPeople observable to undefined.

I have eliminated down to the data bind markup as when i remove that my observable array does not set anything to undefined.

Here is how i am binding my observables/observableArray to the elements.

<select data-bind="options: ObservableArray.People, value: ObservableArray.SelectedPeople, optionsText: 'Name'"></select>
  • ObservableArray.People = Observable Array of objects - works fine and renders all the dropdown options

  • ObservableArray.SelectedPeople = Observable

Both have the 'Name' object defined to match the optionsText. It works perfectly when selecting data from scratch but when i try have predefined data in it the Observable.SelectedPeople object keeps getting sent as undefined when it tries to load.

Basically my Observable.SelectedPeople has a object on that which should predefined the value of that select and the object 100% matches one of the dropdown ObservableArray.People options. I need it not to set Observable.SelectedPeople to undefined and populate the select box.

Can anyone see why this is happening.

Thanks

1
You should check out the value that is assigned to the Observable.SelectedPeople after you select a value from the dropdown. That value should be a property defined in the objects bound to the dropdown. You should be pushing the value of that property to Observable.SelectedPeople. - gkb
Observable.SelectedPeople has a default value which should populate the Observable.People to the one which is set.. @gkb - user4058171
Look at this post and see how the optionsValue attribute has been used in the select control stackoverflow.com/questions/13587230/… - gkb

1 Answers

1
votes

...and the object 100% matches one of the dropdown ObservableArray.People options.

This line makes me suspicious of whether you're using an actual reference to the object, or just an object that is similar.

For example, this will not work:

var options = [{ id: 1 }, { id: 2 }, { id: 3}];
var selectedOption = ko.observable({ id: 1 });

Knockout does not perform some sort of deepEquals comparison; if it sees a non-primitive, it does a reference check. options[0] !== { id: 1 }, so this initial selection is not valid.

The code below will work, because you're using an actual object from the array you use in your select element:

var options = [{ id: 1 }, { id: 2 }, { id: 3}];
var selectedOption = ko.observable(options[0]);