我遇到类似于这个问题的问题。KnockoutJS - populating second combobox based on value selected in first combobox,而不是我使用Select元素的组合框。我有一个主选择元素,当选择一个选项时,它将向第二个Select选项的模型发送一个值并填充可观察数组。我的问题是选项字段中没有显示选项。我已经完成了对控制台的写入,并且数组确实有对象,模型似乎没有更新。
这是我的JSFIDDLE https://jsfiddle.net/gauldivic/bjsswdqu/37/
HTML:
pip
MODEL:
$ pip install pep8
答案 0 :(得分:0)
我能够弄清楚。感谢@Roy j我调用testSelect2(newValue)的方式是替换整个数组而不是向数组中添加元素。 https://jsfiddle.net/gauldivic/L284Lkdk/3/
<强> MODEL:强>
ko.bindingHandlers.option = {
update: function(element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
ko.selectExtensions.writeValue(element, value);
}
};
var mainView = function()
{
this.ts = new testSelect("");
this.ts2 = new testSelect2();
}
function testGroup(label, children) {
this.label = ko.observable(label);
this.children = ko.observableArray(children);
}
function testOption(label, property) {
this.label = ko.observable(label);
this.value = ko.observable(property);
}
function testGroup2(label, children) {
this.label = ko.observable(label);
this.children = ko.observableArray(children);
}
function testOption2(label, property) {
this.label = ko.observable(label);
this.value = ko.observable(property);
}
function testSelect2(content,selectedValue)
{
//alert(content);
this.groups2 = ko.observableArray([]);
this.groups2.push(new testGroup("Letters", [new testOption("X","42")]));
this.selectedOption = ko.observable(selectedValue);
this.specialProperty = ko.computed(function(){
var selected = this.selectedOption();
return selected ? selected : 'unknown';
}, this);
};
var testSelect = function(selectedValue)
{
this.groups = ko.observableArray([]);
this.groups.push(new testGroup("Letters",[new testOption("A","1"),new testOption("B","2")]));
this.selectedOption = ko.observable(selectedValue);
this.specialProperty = ko.computed(function(){
var selected = this.selectedOption();
return selected ? selected : 'unknown';
}, this);
this.selectedOption.subscribe(function(newValue)
{
if(newValue != -1)
{
//alert(newValue);
//console.log(mv.ts2.groups2.push(new testGroup("Letters",[new testOption("C","3"),new testOption("D","4")])));
//mainView.ts2.getData(newValue);
if(newValue == 1)
{
mv.ts2.groups2.removeAll();
mv.ts2.groups2.push(new testGroup("Letters",[new testOption("C","3"),new testOption("D","4")]));
//console.debug(groups2());
}
else if(newValue == 2)
{
mv.ts2.groups2.removeAll();
mv.ts2.groups2.push(new testGroup2("Letters",[new testOption2("E","5"),new testOption2("F","6")]));
};
}
else
{
mv.ts2.groups2.removeAll();
}
});
};
var mv = new mainView();
ko.applyBindings(mv);