我有一个下拉列表(选择/选项),它应该在更改时进行整页刷新(重新加载)..(我在更改时设置cookie值...)
会发生什么:
当我在subscribe中使用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"));
});
答案 0 :(得分:1)
尝试将selectedDepartment的初始值设置为undefined而不是0.现在,您的下拉列表将使用初始值进行渲染,该初始值不会存在于选项列表中(因为选项后来从ajax调用到达)因此,它必须将selectedDepartment observable从0修改为undefined,这将触发您的订阅。
{
"$schema": "http://json-schema.org/draft-06/schema#",
"oneOf": [
{
"properties": {
"A": {"type": "number"},
"B": {"type": "null"},
"C": {"type": "null"},
"D": {"type": "null"}
},
"required": ["A"]
},
{
"properties": {
"A": {"type": "null"},
"B1": {"type": ["number","null"]},
"B2": {"type": ["number","null"]},
"B3": {"type": ["number","null"]}
},
"anyOf": [
{"required": ["B1"]},
{"required": ["B2"]},
{"required": ["B3"]}
]
},
{
"properties": {
"A": {"type": "null"},
"B1": {"type": "null"},
"B2": {"type": "null"},
"B3": {"type": "null"}
}
}
]
}