【发布时间】:2015-10-26 12:08:45
【问题描述】:
我使用knockout的订阅功能来获取第一个下拉列表的选定值来绑定第二个下拉列表中的值。我将选定的下拉列表值存储在会话中,并在刷新时更改下拉列表的值。此时订阅被调用了两次,结果我在下拉列表中重复了每个值。
self.getcountry = function () {
try {
//code
$.ajax({
//code
statusCode: {
200: function (response) {
$.each(response, function (index, data) {
self.country.push(data);
})
if(SESSIONVALUES!=null)
{
for (var i = 0; i < SESSIONVALUES.length; i++) {
var COUNTRYbind=SESSIONVALUES[i].vCOUNTRY;
$('#country option').filter(function () { return $.trim($(this).val()) == parseInt( COUNTRYbind); }).attr('selected', true);
$('#country ').change();
self.selectedCountry(COUNTRYbind);// this is used to trigger the subscribe function
}
}
}
}
});
} catch (exception) { }
};
这是订阅函数方法,
self.selectedCountry.subscribe(function (newValue) {
//code
try {
$.ajax({
//code
statusCode: {
200: function (response) {
$.each(response, function (index, data) {
self.state.push(data);
})
if(SESSIONVALUES!=null)
{
for (var i = 0; i < SESSIONVALUES.length; i++) {
var statebind=SESSIONVALUES[i].vstate;
$('#states option').filter(function () { return $.trim($(this).val()) == parseInt(statebind); }).attr('selected', true);
$('#states').change();
}
}
}
}
});
} catch (Exception) { }
});
【问题讨论】:
-
您应该使用您的视图模型来设置选项。
-
我很确定 $('#country ').change() 和 self.selectedCountry(COUNTRYbind);都会触发您的订阅事件。 (不是 100% 我有一段时间没碰过淘汰赛)
标签: javascript jquery asp.net-mvc-4 knockout.js