I'm really struggling to figure out how to asynchronously bind my cascading Select2 drop-down fields using knockoutJS.
Everything works perfectly fine when the data is static within the function, but as soon as I introduce an asynchronous ajax call, the binding happens before the response is received and things fall apart.
If anyone could point me in the right direction or spot any issues, I would greatly appreciate it as I am fairly new to knockout.js.
Knockout
var viewModel = {
togaMakers: buildData(),
selectedInstitution : ko.observable(),
selectedLevel : ko.observable(),
selectedFaculty : ko.observable()
};
viewModel.togaLevels = ko.computed(function(){
if(viewModel.selectedInstitution()){
var make = ko.utils.arrayFirst(viewModel.togaMakers,function(item){
//console.log(item.text,viewModel.selectedInstitution());
return item.text===viewModel.selectedInstitution();
});
return make.childOptions;
}
});
viewModel.togaFaculties = ko.computed(function(){
if(viewModel.selectedLevel()){
var type = ko.utils.arrayFirst(viewModel.togaLevels(),function(item){
//console.log(item.text,viewModel.selectedLevel());
return item.text===viewModel.selectedLevel();
//console.log("Answer:" + item);
});
return type.childOptions;
}
});
ko.cleanNode(viewModel);
ko.applyBindings(viewModel);
buildData()
function buildData() {
var gotData = getData();
return gotData.then(function() {
console.log('step 4 - return result');
returnData = gotData;
return returnData;
});
}
getData()
// Fetch all data from an ajax call
function getData() {
var data = { 'action': 'get_data' };
var deferred = new jQuery.Deferred();
return jQuery.post(ajaxurl, data, function(response) {
// console.log(response);
console.log('step 1 - parse ajax data');
var obj = JSON.parse(response);
console.log('step 2 - process received data');
results = processData(obj);
}).done(function() {
console.log('step 3 - ajax parsing & processing data done');
console.log(results);
deferred.resolve(results);
return deferred;
}).fail(function() {
console.log('fail');
});
}