I"m been tasked with doing a POC of KnockoutJS and running into an issue that I just can't figure out.
I want to retrieve the data from a service using Ajax and then populate the form with ko.mapping.fromJS(). My form will not populate when I call the mapping from within the success function of the ajax call. If I move it outside the success then it works fine.
UPDATE: I do know that the load function does get called in my jsfiddle (put an alert inside there and it does fire) but the form does not populate..
var planDesignData = {
RecordID: '1124',
Name: "Main"
};
var PlanDesignModel = function () {
var self = this;
//*** As soon as I move this line inside the sucess the input doesn't get populated
self.planDesign = ko.mapping.fromJS(planDesignData);
self.load = function () {
$.ajax({
type: "POST",
url: "/echo/json/",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var loadedPD = {};
//I want to run the mapping here
}
});
}
}
$(document).ready(function () {
var viewModel = new PlanDesignModel();
viewModel.load();
ko.applyBindings(viewModel);
});
Any help would be greatly appreciated.
Here is example
All you need to do is send data to /echo/json
.
I did do a defer
in this example:
$(document).ready(function () {
var viewModel = new PlanDesignModel();
$.when(viewModel.load).always(function(){
ko.applyBindings(viewModel);
});
});
But everything works just fine:
success: function (data) {
var loadedPD = {};
console.log(data);
self.planDesign = ko.mapping.fromJS(planDesignData);
//I want to run the mapping here
}
Note, I did put 1 second delay:
data: {
json: JSON.stringify({
RecordID: '1124',
Name: "Main"
}),
delay: 1
},