0
我很難理解如何使用knockoutJS異步綁定我的級聯Select2下拉字段。在Knockout.js中異步應用綁定
當要填充的數據在函數中是靜態的時,代碼完美工作,但在使用異步ajax調用時不起作用,因爲在接收到響應之前執行綁定。
任何人都可以引導我進入正確的方向或發現問題,因爲我是一個knockout.js初學者?
敲除
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()
// Get all data from 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');
});
}
謝謝你,這是一個非常有用的超級快速回復!你我的朋友拯救了這一天! – Ben