I have a Knockout object mapped from a JSON object. A value of that knockout object is databound to an input element.
I have also bound a google places autocomplete to that same input element.
The value referenced by the knockout object tells me the value of what I have typed in (not selected, so it would be ‘bar’).
The value of the input box is the correct value (the location I have chosen, ‘Barnet, United Kingdom’).
Here is a JSFiddle that demonstrates the problem…
http://jsfiddle.net/twistedinferno/CPEMk/
Why do the two values differ and can I get the selected value as my bound value? (preferably without the need of another property on my KO object)
Updated JSFiddle here
This is normal behavior. Knockout registers its value bindings to events it is aware of such as
afterkeypressorblur. It cannot ‘detect’ changes made by other frameworks such Google Places API by default. So, in order to work, you need to write some code that pushes events from the other framework to Knockout.In this case, Google Places Autocomplete API supports a
place_changedevent. I’ve incorporated this event in my updated Fiddle to showcase a working example. See the Google documentation for more information about this event. The most important bit is:However, if you intend to use this functionality more than once, I strongly suggest you wrap this behavior in a custom Knockout binding.
Here’s an excellent article about custom Knockout bindings. If you scroll all the way down to the last chapter, you will see an example of a Knockout binding that wraps around a third party control. You will want to do the same for Google Places Autocomplete, so you can handle three aspects of working with this control:
place_changedevent.Using a custom knockout binding will look something like this:
Good luck!