我已经开始使用 knockoutjs 并做一些简单的绑定/依赖绑定。我的目标是<select>
根据另一个列表的值填充1 个<select>
列表。两者都是从我的 asp.net 网络服务的 ajax 调用中加载的。
所以我有两个<select>
清单
<select id="make" data-bind="options: availableMakes, value: selectedMake, optionsText: 'text', optionsCaption: 'Choose a make'"></select>
<select id="model" data-bind="options: availableModels, value: selectedModel, optionsText: 'text', optionsCaption: 'Choose a model'"></select>
然后我的 javascript 看起来像这样:
$(function () {
// creating the model
var option = function (text, value) {
this.text = text;
this.value = value;
}
// creating the view model
var searchModel = {
availableMakes: ko.observableArray([]),
availableModels: ko.observableArray([]),
selectedMake: ko.observable(),
selectedModel: ko.observable()
}
// adding in a dependentObservable to update the Models based on the selected Make
searchModel.UpdateModels = ko.dependentObservable(function () {
var theMake = searchModel.selectedMake() ? searchModel.selectedMake().text : '';
if (theMake != '') {
$.ajax({
url: "/data/service/auction.asmx/GetModels",
type: 'GET',
contentType: "application/json; charset=utf-8",
data: '{make:"' + theMake + '"}',
success: function (data) {
var makes = (typeof data.d) == 'string' ? eval('(' + data.d + ')') : data.d;
var mappedModels = $.map(makes, function (item) {
return new option(item.text, item.value);
});
searchModel.availableModels(mappedModels);
},
dataType: "json"
});
}
else {
searchModel.availableModels([]);
}
return null;
}, searchModel);
// binding the view model
ko.applyBindings(searchModel);
// loading in all the makes
$.ajax({
url: "/data/service/auction.asmx/GetMakes",
type: 'GET',
contentType: "application/json; charset=utf-8",
data: '',
success: function (data) {
var makes = (typeof data.d) == 'string' ? eval('(' + data.d + ')') : data.d;
var mappedMakes = $.map(makes, function (item) {
return new option(item.text, item.value);
});
searchModel.availableMakes(mappedMakes);
},
dataType: "json"
});
});
目前这可以按预期工作,但我认为我做错了,因为代码看起来很长,我可以在不使用更少代码的情况下做到这一点。另外,我加载的availableModels
方式显然是不正确的,因为我使用了一个名为dependentObsevable UpdateModels
,我添加它是为了availableModels
根据selectedMake().text
我希望这是有道理的,你可以指出一个改进的版本吗?或者简单地告诉我如何根据 Make 选择重新加载模型?
非常感谢,