Reputation: 2622
I used the following ajax code to obtain an object called Client by it's id like so:
$.ajax({
url: "api/client/GetClient/" + id,
contentType: 'json',
success: function (result) {
model.selectedClient(result);
$("#loader").hide();
},
failure: function (result) {
alert(result.d);
$("#loader").hide();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("An error occurred, please try again.");
$("#loader").hide();
}
});
But although the selectedClient is an observable its values aren't so if I bind the value of say selectedClient().Name to a textbox, changing the textbox doesn't update the value. I don't want to create a function and a push method, I like being able to simply put the returned object in so future changes are seamless. What can I do to make them observable values?
Upvotes: 0
Views: 867
Reputation: 16900
selectedClient
should be observable and so does it's properties if you want to reflect the changes in UI.
How are you creating your selectedClient?
You should actually create a class like this:
Client = function(data){
ko.mapping.fromJS(data,{},this);
}
have a property in your viewmodel like this:
selectedClient = ko.observable()
and your success method of ajax should be:
success: function (result) {
model.selectedClient(new Client (result));
$("#loader").hide();
}
This will make sure whenever your object's properties changes, your view reflects it. For more information, you can refer this link:
http://knockoutjs.com/documentation/plugins-mapping.html
Upvotes: 1