我有一个下拉菜单(选择/选项),当更改时应执行整页刷新(重新加载)。(更改时我正在设置Cookie值...)
怎么了 :
当我在订阅中使用window.location.reload()时(请参见下面的代码),它最终以无限重载循环结束。
我如何避免这种情况?
选择控制
<select id="ddlSelectDepartment" class="form-control" data-bind="options: departments, optionsCaption: 'Alle', optionsText: 'name', optionsValue: 'id', value: selectedDepartment"></select>
淘汰赛处理
$(document).ready(function() {
var selDepCookie = JSHelpers.readCookie("seldep");
console.log("COOKIEMONSTER! " + selDepCookie);
var DepModel = function() {
var self = this;
self.departments = ko.observableArray();
self.selectedDepartment = ko.observable(0);
self.selectedDepartment.subscribe(function (latest) {
//console.log("Input changed");
JSHelpers.setCookie('seldep', latest);
window.location.reload(); // this ends in a infinite loop !
}, self);
}
var urlForSelectDepartment = 'api/Customer/GetDepartmentsFull';
$.ajax({
type: 'GET',
url: urlForSelectDepartment,
success: function (data) {
depmodel.departments(data);
},
error: function (e) {
console.log(e);
},
dataType: "json",
contentType: "application/json"
});
var depmodel = new DepModel();
ko.applyBindings(depmodel,
document.getElementById("selectDepartmentContainer"));
});
最佳答案
尝试将selectedDepartment的初始值设置为undefined而不是0。现在,您的下拉列表将使用选项列表中不存在的初始值呈现(因为这些选项稍后会从ajax调用中到达)将可观察的selectedDepartment的可观察性从0修改为undefined,这将触发您的订阅。
self.selectedDepartment = ko.observable(undefined);