Hello,
I have set up my knockout objects as follows
this.ns = (function (ns) {
ns.View = function () {
var self, viewModel;
self = this;
viewModel = new ns.ViewModel();
self.init = function () {
console.log("Calling View Model Get Data Method");
viewModel.getData();
console.log("Finished Calling View Model Get Data Method");
console.log("Started ko Bindings");
ko.applyBindings(self, document.getElementById("View"));
console.log("Finished ko Bindings");
};
};
return ns;
}(this.ns || {}));
this.ns = (function (ns) {
ns.ViewModel = function () {
var self;
self = this;
self.Id = ko.observable();
self.Name = ko.observable();
self.getData = function () {
$.ajax({
url: url,
dataType: 'json',
type: 'POST',
data: {},
contentType: "application/json;charset=utf-8",
success: function (response) {
console.log("Started Populating ViewModel");
self.Id(response.Id);
self.CheckListId(response.CheckListId);
console.log("Finished Populating ViewModel");
}
});
};
};
return ns;
}(this.ns || {}));
This consists of a View and ViewModel. The View calls the ViewModel getData function which retrieves the data from the server and then poulates itself.
The problem I am having is the order that the events are taking place. Looking at the console log statements I get the following
Started Log
Calling View Model Get Data Method
Started Ajax Call to Data
POST
http://localhost/url.asmx/RetrieveData 200 OK
Finished Ajax Call to Data
Finished Calling View Model Get Data Method
Started ko Bindings
Finished ko BindingsFinished Log
Started Populating ViewModel
Finished Populating ViewModelThis seems to show that the Ajax call is causing issues with the ko.bindings that are happening before the viewModel is populated which causes the bound data to be empty. I can confirm this by using the following in the HTML which displays as empty
<div class="layout-section tests-section" id="View" >
<pre data-bind="text: ko.toJSON($data, {}, 2)"></pre>
</div>
Unless I move the following line
console.log("Started ko Bindings");
ko.applyBindings(self, document.getElementById("View"));
console.log("Finished ko Bindings");
to the end of the sucess ajax call at which point everything works as expected, but I do not want to have my ko.applyBindings call in the ViewModel.
I have had a look online and can not find any references to anyone else having the same issue, but did find the following on a similar topic suing computeds, but my returned data is not a computed
https://github.com/knockout/knockout/wiki/Asynchronous-Dependent-ObservablesI have also looked at
https://api.jquery.com/promise/but wondered if anyone has had similar issues or could suggest any other techniques, URLs I could use to allow the Ajax call to complete before the ko.applyBindings is called? Also not sure if there are any built in Knockout methods I could use to deal with this?