所以这是我的样本数据。以json格式加载表单服务器构造成下面的objec图。 它的一系列“Choice”对象每个都有 id,name,stages& currentStageId 属性。 “选择”对象中的“阶段”属性是“Stage”对象的数组,其中包含 id,name& 值属性。“选择”对象将经历从“第一阶段”到“第四阶段”的各个阶段,因此用户可以从给定下拉列表中选择“阶段”保存。 “currentStageId”是存储舞台对象“id”的属性,它将在哪个阶段提供相应的“选择”对象
注意:每个选项可以有不同类型的阶段,以简化尽可能简单
即对于选择1,当前保存的阶段是4
var data = [
new Choice({
id: 1,
name: "One",
stages: [
new Stage({
id: 1,
name: "First Stage",
value: 25
}),
new Stage({
id: 2,
name: "Second Stage",
value: 50
}),
new Stage({
id: 3,
name: "Third Stage",
value: 75
}),
new Stage({
id: 4,
name: "Fourth Stage",
value: 100
})],
currentStageId: 4
}),
new Choice({
id: 2,
name: "Two",
stages: [
new Stage({
id: 1,
name: "First Stage",
value: 25
}),
new Stage({
id: 2,
name: "Second Stage",
value: 50
}),
new Stage({
id: 3,
name: "Third Stage",
value: 75
}),
new Stage({
id: 4,
name: "Fourth Stage",
value: 100
})],
currentStageId: 3
}),
new Choice({
id: 3,
name: "Three",
stages: [
new Stage({
id: 1,
name: "First Stage",
value: 25
}),
new Stage({
id: 2,
name: "Second Stage",
value: 50
}),
new Stage({
id: 3,
name: "Third Stage",
value: 75
}),
new Stage({
id: 4,
name: "Fourth Stage",
value: 100
})],
currentStageId: 2
})];
这是“选择”& “Stage”用于保存数据的模型和用于绑定的 ViewModel
function ViewModel(data) {
var self = this;
self.choices = ko.observableArray(data);
//dont require pre selection so kept it with empty observable so it
//will be set to first item in the dropdown list
self.selectedChoice = ko.observable();
}
function Choice(data) {
//debugger;
this.id = data.id;
this.name = data.name;
//require pre selection of stage as choice can go through no of
//stages and selected stage name and value will be stored
this.selectedStage = ko.observable(ko.utils.arrayFirst(data.stages, function (item) {
return item.id === data.currentStageId;
}));
this.stages = ko.observableArray(data.stages);
}
function Stage(data) {
this.id = data.id;
this.name = data.name;
this.value = data.value;
}
ko.applyBindings(new ViewModel(data));
这是我的观点
<select data-bind="options: choices, optionsText: 'name', value: selectedChoice"></select>
<select data-bind="options: selectedChoice().stages, optionsText: 'name', value: selectedChoice().selectedStage"></select>
Knockout.js 2x版
以下是js中的Working sample with KO 2x
Knockout.js 3x版
最后是实际部分。问题!
提前致谢。
答案 0 :(得分:0)
我认为这与2. Bindings are now refreshed independently有关
现在,您应该使用selectedChoice
移出options
绑定,例如
<div data-bind="with: selectedChoice">
<select data-bind="options: stages, optionsText: 'name', value: selectedStage"></select>
</div>