我想到了两个解决方案:
- 订阅
DropdownA
viewmodel 中的 observableArray 并替换 observableArray 中的城市范围,DropdownB
只要它发生变化
- 使用可观察的数据上下文:使用可观察的作为选项源,以便您在需要时也可以更改它。像第一个一样订阅并
DropdownA
在更改时替换整个城市集合
我会选择第二个,因为那更干净。
这是我为您制作的 jsfiddle 示例。
html:
<select data-bind="options: dropdownA, value: dropdownAValue">
</select>
<select data-bind="options: dropdownB">
</select>
JS:
var viewModel = function() {
var _this = this,
dataSource1,
dataSource2;
dataSource1 = ["Hello"];
dataSource2 = ["World"];
_this.dropdownA = ko.observableArray(["A", "B"]);
_this.dropdownB = ko.observable(dataSource1);
_this.dropdownAValue = ko.observable();
_this.dropdownAValue.subscribe(function() {
if (_this.dropdownAValue() == "A") {
_this.dropdownB(dataSource1);
} else {
_this.dropdownB(dataSource2);
}
});
};
ko.applyBindings(new viewModel());
然后很容易在多行中使用这个概念:http: //jsfiddle.net/jGRQH/
html:
<table data-bind="foreach: rows">
<tr>
<td>
<select data-bind="options: $root.dropdownA, value: dropdownAValue">
</select>
</td>
<td>
<select data-bind="options: dropdownB">
</select>
</td>
</tr>
</table>
JS:
var rowViewModel = function(dataSource1, dataSource2) {
var _this = this;
_this.dropdownB = ko.observable(dataSource1);
_this.dropdownAValue = ko.observable();
_this.dropdownAValue.subscribe(function() {
if (_this.dropdownAValue() == "A") {
_this.dropdownB(dataSource1);
} else {
_this.dropdownB(dataSource2);
}
});
};
var mainViewModel = function() {
var _this = this,
dataSource1,
dataSource2,
addRow;
dataSource1 = ["Hello"];
dataSource2 = ["World"];
addRow = function () {
_this.rows().push(new rowViewModel(dataSource1, dataSource2));
};
_this.rows = ko.observableArray();
_this.dropdownA = ko.observableArray(["A", "B"]);
addRow();
addRow();
addRow();
};
ko.applyBindings(new mainViewModel());