I am trying to bind a model coming from the server over json to a viewmodel I create on the client and then bind it using Knockout.js to display the data. I have the following code
function tireRunDataViewModel() {
var self = this;
self.load = function() {
$.jQuery.post('./GetTireRunModel', { outingID: '@Model' }, function (result) {
self.data = ko.mapping.fromJS(result);
} , "json");
};
self.load();
}
var viewModel = new tireRunDataViewModel();
ko.applyBindings(viewModel);
It appears as though self.data is not being set before the ko.applyBindings is being done. Why is this and what can I do to make sure the self.data is being filled out before the applyBindings is being done?
The call to
$.jQuery.postis asynchronous, so the callback does not execute until it completes, which is afterko.applyBindingsis called.A couple of options:
you could call
ko.applyBindingsin your callback. If your application is not more complicated than this, then it can be an option to apply bindings after the AJAX call has completed.you could create
self.dataas an observable and then updated it in the callback like:self.data(ko.mapping.fromJS(result));. Then in your UI you could use awithbinding ondataaround the UI that depends ondata, so that it is not rendered until it is ready.Quick simulation of it: http://jsfiddle.net/rniemeyer/Wf8E8/