I am encountering an issue with updating data on the UI after making an asynchronous call to a web service and receiving JSON back. The JSON object that I receive has multiple properties, although only one is shown in the code snippet below for simplicity. To map the JSON data to the object properties, I am using ko.mapping.fromJS function. However, the UI does not update with the fetched data. Manually updating the observable works fine, but not when using ko.mapping.fromJS.
Javascript
function AppViewModel() {
var self = this;
self.firstName = ko.observable("Bert");
$.ajax({
dataType: 'json',
async: true,
type: 'POST',
url: '/echo/json/',
data: {
json: '{"firstName":"Bob1"}'
}
}).done(function(data) {
console.log(data);
//self.firstName(data.firstName);//This works
self = ko.mapping.fromJS(data); //This doesn't
console.log(self.firstName());
}).fail(function(jqxhr, textStatus, error) {
alert('there was an error');
});
}
// Activates knockout.js
var avm = new AppViewModel();
ko.applyBindings(avm);
HTML
<p>First name: <strong data-bind="text: firstName"></strong></p>
You can run the jsfiddle where you will notice that the line below works correctly
self.firstName(data.firstName);//This works
However, the following line does not update the UI
self = ko.mapping.fromJS(data); //This doesn't