我正嘗試使用knockoutJS填充級聯select2下拉列表。 使用類似於function staticbuildData()
中的靜態數據時,代碼似乎工作正常,但在使用函數function buildData()
時會引發錯誤。ObservableArray中的第一個數組項目
的第一個下拉在第一個下拉以下錯誤填充數據正確但是,在項目的選擇是拋出:
Uncaught TypeError: Cannot read property 'childOptions' of null
事實證明,下面一行是無法找到孩子的選擇並返回NULL:
var make = ko.utils.arrayFirst(viewModel.togaMakers,function(item)
我能想到的唯一的事情就是staticbuildData()
是返回一個數組,而buildData()
是返回一個observableArray,因此沒有找到正確的子選項。
我在正確的軌道上還是有人有一個想法,爲什麼會發生這種情況?
淘汰賽
var viewModel = {
togaMakers: buildData(),
// togaMakers: staticbuildData(),
selectedInstitution : ko.observable(),
selectedLevel : ko.observable(),
selectedFaculty : ko.observable()
};
viewModel.togaLevels = ko.computed(function(){
if(viewModel.selectedInstitution()){
console.log(buildData());
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 dataContainer = ko.observableArray([]);
getData().then(function(newData) {
parsed = JSON.parse(newData);
processed = processData(parsed);
dataContainer(processed);
});
return dataContainer;
};
staticBuildData
function staticbuildData(){
var uomBachelor = new cascadingOption({
text: 'Bachelor Degree',
childOptions : [
new cascadingOption({
text: 'Faculty of Enviroment'
}),
new cascadingOption({
text: 'Faculty of Education'
})
]
});
var uomMaster = new cascadingOption({
text: 'Master Degree',
childOptions : [
new cascadingOption({
text: 'Faculty of Law'
}),
new cascadingOption({
text: 'Faculty of Dental & Surgery'
})
]
});
var uom = new cascadingOption({
text: 'University 1',
childOptions : [uomBachelor, uomMaster]
});
var mdx = new cascadingOption({
text: 'University 2',
childOptions : [
new cascadingOption({
text:'Bachelor Degree',
childOptions : [
{text: 'Q5'},
{text: 'Q7'}
]
}),
new cascadingOption({
text:'Master Degree',
childOptions : [
{text: 'A3'},
{text: 'A4'},
{text: 'A6'}
]
})
]
});
return [uom, mdx];
}
我可以看到你的html或jsfiddle嗎? –