$.getJSON
in asynchronous. The result data is available in the callback only. It is not available as the return value of $.getJSON
The documentation never mentions a return value.
$.getJSON("/api/administrators", null, function(adminData, status, xhr){
var viewModel = {
administrators: ko.observableArray(adminData)
};
ko.applyBindings(viewModel);
});
If you need to make separate AJAX calls, you should use jQuery.when
See Wait until all jQuery Ajax requests are done?
$.when($.ajax("/api/administrators"), $.ajax("api/roles")).done(function(resp1, resp2){
ko.applyBindings({
administrators: ko.observableArray(resp1[0]),
roles: ko.observableArray(resp2[0]);
});
});
Here are some other less than ideal solutions, but it shows you what happens under the hood.
If you don't mind that the requests wait for each other
$.getJSON("/api/administrators", null, function(adminData){
$.getJSON("/api/administrators", null, function(apiRoles){
ko.applyBindings({
administrators: ko.observableArray(adminData),
roles: ko.observableArray(apiRoles);
});
});
});
If you do care, it's more complicated since you need to track that the requests finished
var ajaxAdminData, ajaxApiRoles
$.getJSON("/api/administrators", null, function(adminData, status, xhr){
var ajaxAdminData = adminData;
// If the other call finished, apply the bindings
if (ajaxApiRoles) {
applyBindings();
}
});
$.getJSON("/api/administrators", null, function(apiRoles, status, xhr){
ajaxApiRoles = apiRoles;
// If the other call finished, apply the bindings
if (ajaxAdminData) {
applyBindings();
}
});
function applyBindings() {
ko.applyBindings({
administrators: ko.observableArray(ajaxAdminData),
roles: ko.observableArray(ajaxApiRoles);
});
}