I have a strange problem, at least I think it is strange.
The following will show nothing:
<input type="text" data-bind="value: selectedAddress.street1" />
But, if binded like this then it shows the correct value, but doesn’t update (shows the value but does not seem to bind to object):
<input type="text" data-bind="value: ko.toJS($data).selectedAddress.street1" />
I checked if the selectedAddress object actually contains data with:
JSON.stringify(ko.toJS(selectedAddress), null, 2)
And it does
{
"id": 5631,
"street1": "Some Adress 43",
"street2": null,
"postcode": "15850",
"city": "GhostTown",
"country": "UK",
"addressTypes": []
}
How to get the input field to correctly bind to the object property and display/update value accordingly?
ViewModel:
var theViewModel = function() {
var self = this;
self.no = ko.observable();
self.name = ko.observable();
self.addresses = ko.observableArray([]);
self.selectedAddress = ko.observable(new Address());
...
}
What am I doing wrong?
Parenthesis are optional only in some cases, but not when referring to a property of an object (that may or may not be the value of an observable). Therefore, you need to explicitly use parenthesis to get the value of the observable
selectedAddress. Then, you may refer to the propertystreet1of this object (parenthesis are now optional):