Knockout的新手,将我的MVC应用程序从使用Telerik MVC组合框迁移到Knockout。 我使用Ajax生成两个数组,并使用以下内容将它们绑定到Knockout:
<select data-bind='options: myFirstList, optionsText: "Text", optionsCaption: "Select...", value: 0'> </select>
<select data-bind='options: mySecondList, optionsText: "Text", optionsCaption: "Select...", value: 0'> </select>
function myViewModel() {
this.myFirstList = ko.observableArray([]);
this.mySecondList = ko.observableArray([]);
}
var objVM = new myViewModel();
ko.applyBindings(objVM);
Using Ajax:
$.ajax({
url: '/Home/CheckWord',
type: 'POST',
data: {
cword: wordtocheck
},
success: function (data) {
.....
}
objVM.mySecondList(stateList[0]);
var fnArray = [];
for (var k = 0; k < data.fnList.length; ++k) {
fnArray[k] = { Text: data.fnList[k], Value: k };
}
objVM.myFirstList(fnArray);
},
error: function () {
alert("n");
}
});
无法弄清楚如何根据从第一个列表中选择的项目更改第二个选择列表,并从第二个列表中选择如何触发带有项目的Javascript操作。 如果有人可以给我一个例子,我将不胜感激。
答案 0 :(得分:0)
,绑定&#39;值&#39;可观察的
<select data-bind='options: myFirstList, optionsText: "Text",
optionsCaption: "Select...", value: myFirstListSelected'> </select>
<select data-bind='options: mySecondList, optionsText: "Text",
optionsCaption: "Select...", value: mySecondListSelected'> </select>
在JS中,使用subscribe来监听模型的更改事件
function myViewModel() {
var self = this;
self.myFirstList = ko.observableArray([]);
self.mySecondList = ko.observableArray([]);
self.myFirstListSelected = ko.observable();
self.mySecondListSelected = ko.observable();
// when first selected changes
self.myFirstListSelected.subscribe(function(newVal) {
// ignore blank selection
// or you can clear second list when user deselects first one.
// if (newVal == null) {
// self.mySecondListSelected(undefined);
// self.mySecondList.removeAll();
// return;
// }
if (newVal == null) return;
$.ajax({
//...
data: { cword: newVal },
success: function (data) {
//...
// clear selected
self.mySecondListSelected(undefined);
// reload second list
self.mySecondList(stateList[0]);
//...
}
//...
});
});
// when second selected changes
self.mySecondListSelected.subscribe(function(newVal) {
//... beware newVal could be null or undefined when user deselects it.
});
}