0
我有兩個連接的下拉列表,我正在使用Knockout。他們都使用一個簡單的Value,Text對來填充ajax調用。 當我去改變價值,但我總是從選定的列表中獲得以前的值。因此,如果默認的RegionCode值爲「-1」,則當我將其更改爲另一個區域時,將傳遞給loadLocationList的第一個RegionCode值將爲「-1」,即使實際選定的值與通過檢查元素或者通過JQuery的敲出先前選定的值
型號
define([
'util',
'locationService',
'jquery',
'knockout',
'knockoutmapping',
function(util, svc, $, ko, mapped) {
var LocationViewModel = function(regionCodes, regionCode, locationCodes, locationCode, currentYear) {
var self = this;
self.CurrentYear = currentYear;
self.RegionCode = ko.observable(regionCode)
self.RegionCodes = ko.observableArray(regionCodes)
self.LocationCode = ko.observable(locationCode)
self.LocationCodes = ko.observableArray(locationCodes)
self.loadLocationList = function() {
self.LocationCodes([]);
var locationListCallback = function(data){
for (var i = 0; i < data.length; i++) {
self.LocationCodes.push(new SelectListPair(data[i].Value, data[i].Text));
}
}
svc.getLocationsInRegion(self.CurrentYear, self.RegionCode, true, locationListCallback);
}
}
var SelectListPair = function (value, text) {
this.Value = ko.observable(value);
this.Text = ko.observable(text);
}
return function summaryViewModel() {
var self = this;
self.LocationSummaryViewModel = ko.observable();
var initViewModel = function() {
$.ajax({
url: 'Url here',
success: function(vm) {
var locationVM = vm.LocationSummaryViewModel;
var selectListArray = locationVM.LocationList;
var selectList = [];
for (var i = 0; i < selectListArray.length; i++) {
var SelectListPair = {
Value: ko.observable(selectListArray[i].Value),
Text: ko.observable(selectListArray[i].Text),
};
selectList.push(SelectListPair);
}
var location = [new SelectListPair("-1", "Please select a location")];
self.LocationSummaryViewModel(new LocationViewModel(vm.CurrentYear, selectList, "-1", location, "-1"));
},
});
}
}
self.initViewModel();
});
查看
<!-- ko with: LocationSummaryViewModel() -->
<div class="panel panel-default" data-bind="visible: Visible()">
<div class="panel-heading">
<div class="row">
<div class="col-md-4">
Location Summary
</div>
<div class="col-md-4">
<select class="form-control" data-bind="
options: RegionCodes(),
disable: RegionCodes().length === 1,
optionsText: 'Text',
optionsValue: 'Value',
event: {change: loadLocationList },
value: RegionCode">
</select>
</div>
<div class="col-md-4">
<select class="form-control" data-bind="
options: LocationCodes(),
disable: LocationCodes().length === 1,
optionsText: 'Text',
optionsValue: 'Value',
value: LocationCode">
</select>
</div>
</div>
</div>
<div class="panel-body">
Neat content
</div>
<div class="panel-footer">
</div>
</div>
<!-- /ko -->
不要綁定到select上的事件。改爲訂閱'value'變量。然後你知道它什麼時候改變了。 –
@RoyJ非常感謝! – adc90