Reputation: 145
Refer to this Fiddle: http://jsfiddle.net/44AwW/3/
After 3 seconds, a new 'Place' gets added to the <table>
(as a way to simulate ajax-loaded data).
'Place' is a simple JS object, but two of its properties (City and PlaceType) are objects themselves - each with an 'id' and 'name' property.
var Place = {
id: 1,
name: "Paradiso",
placeType: {
id: 1,
name: "Concert Hall"
},
city: {
id: 1,
name: "Amsterdam"
},
address: "Somewhere in the city"
}
When clicking the Edit option, the values from the Place in the grid should be set in the form: the City and Place Type <select>
s should show "Amsterdam" and "Concert Hall", respectively, but only the 'name' and 'address' are shown/set.
Now, when I add a new Place through the form itself and the Add button, and I click the Edit link of that just-created Place in the table, all of its properties are indeed set and shown in the form, including the City and PlaceType.
So the Places created through the form and added to the observableArray (and therefore shown on the <table>
) have all their property values shown correctly when using the Edit button, but when the Places are added programmatically (as in the fiddle) or through ajax, the City and PlaceType property fail to be set and shown on the form.
What am I missing?
Upvotes: 3
Views: 7495
Reputation: 16688
Javascript compares objects by reference. Objects that simply look the same won't match each other. When you select from the select list, you get a reference to the object stored in cities
or placeTypes
. But when you load an object through ajax, you get a new object that just looks the same.
There are two ways to solve this. The first is to use strings to do the matching. In this case, you'll add an optionsValue
binding to your select
element. The second is to separately look up the object (using something like ko.utils.arrayFirst
) and store that before editing.
I updated your example to show how you can use optionsValue
while only storing the the id
s of the city and place type in your place
objects.
Upvotes: 4
Reputation: 8487
You should use with
binding for editing and particular record. Check out the answer here :
Edit item in knockout observableArray
Upvotes: 0