I have a select element that is bound to a list of complex javascript objects using the options binding:
<select data-bind="options: availableCountries, optionsText: 'countryName', value: selectedCountry, optionsCaption: 'Choose...'"></select>
where availableCountries is an observable array of javascript objects. You can see the full example in this fiddle.
Now, this works fine when I select an item in the list. However, if I need to update the value from some other part of the application, I will only be able to do so if I use the exact same Country object as lies in the availableCountries array. This has also been established in this related question, but unfortunately it does not solve my problems.
In the documentation of the options binding, they anticipate this problem, and say that I should use the optionsValue binding:
Typically you’d only want to use optionsValue as a way of ensuring
that KO can correctly retain selection when you update the set of
available options. For example, if you’re repeatedly getting a list of
“car” objects via Ajax calls and want to ensure that the selected car
is preserved, you might need to set optionsValue to “carId” or
whatever unique identifier each “car” object has, otherwise KO won’t
necessarily know which of the previous “car” objects corresponds to
which of the new ones.
But this unfortunately will not work, as it also affects the value binding – if I set optionsValue to 'countryName', selectedCountry will only contain the name of the country and not the entire object.
I’m looking for a way to combine these. I still want value to be the entire object, but I want the option value comparison to use a specific property that I specify. Basically, something in the lines of:
<select data-bind="options: availableCountries, optionsText: 'countryName', optionsComparator: 'countryName', value: selectedCountry, optionsCaption: 'Choose...'"></select>
However, as far as I can see, this involves modifying the value binding. Do I have any other options? Can I solve this in some other way? Extenders? A custom binding handler?
I’ve made a selected binding that fixes this problem, check my collection of bindings
Demo, the dropdown is at the end of the page
http://jsfiddle.net/H8xWY/8/
https://github.com/AndersMalmgren/Knockout.Bindings
Code