Javascript Knockout.js:observable.subscribe with window.location.reload()导致无限重载循环
我有一个下拉选择/选项,它应该在更改时重新加载整个页面。。我正在设置更改时的cookie值 发生了什么: 当我在subscribe see下面的代码中使用window.location.reload时,它将以无限重载循环结束 我怎样才能避免这种情况 选择控件Javascript Knockout.js:observable.subscribe with window.location.reload()导致无限重载循环,javascript,knockout.js,Javascript,Knockout.js,我有一个下拉选择/选项,它应该在更改时重新加载整个页面。。我正在设置更改时的cookie值 发生了什么: 当我在subscribe see下面的代码中使用window.location.reload时,它将以无限重载循环结束 我怎样才能避免这种情况 选择控件 尝试将selectedDepartment的初始值设置为undefined,而不是0。现在,您的下拉列表呈现的初始值在选项列表中不存在,因为选项稍后从ajax调用到达,因此它必须将selectedDepartment从0修改为undefin
尝试将selectedDepartment的初始值设置为undefined,而不是0。现在,您的下拉列表呈现的初始值在选项列表中不存在,因为选项稍后从ajax调用到达,因此它必须将selectedDepartment从0修改为undefined,这将触发您的订阅
self.selectedDepartment = ko.observable(undefined);
谢谢你的回复@James Spake,它确实起作用了….:现在我只需要找到一些逻辑来获取cookie,并将所选值设置为下拉列表…剩下的唯一问题是。。。当我这样做时:self.selectedDepartment=ko.observejshelpers.readCookieseldep;它再次以无限循环结束..如何将下拉列表中的选定值设置为cookie的值?@TerjeNygård您只需确保您正在设置的值已存在于departments数组中,以便在设置初始值时下拉列表会在列表中找到它。
$(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"));
});
self.selectedDepartment = ko.observable(undefined);