我在我的JavaScript视图模型中使用Knockout有这段代码。一切都按设计工作,除了当我的异步调用返回时,我正在努力使双向绑定更新正常工作。请参阅下面的代码。
var ViewModel = function (counterparty, scenario) {
this.counterparty = ko.observable(counterparty);
this.scenario = ko.observable(scenario);
this.choice = ko.computed(function () {
// Knockout tracks dependencies automatically.
//It knows that fullName depends on firstName and lastName,
//because these get called when evaluating fullName.
return this.counterparty() + " " + this.scenario();
}, this);
this.loginResult = ko.observable("");
// Do an asynchronous request to a rest service
var xmlhttp = new XMLHttpRequest();
var url = 'http://someloginurl';
xmlhttp.open('GET', url, true, 'user', 'pass');
xmlhttp.send(null);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var response = xmlhttp.responseXML;
this.loginResult = "Logged In To RNS Successfully";
} else {
// wait for the call to complete
}
};
this.availableCountries = ko.observableArray([
new Country("UK", 20000),
new Country("France", 30000)]);
this.selectedCountry = ko.observable();
};
var Country =
function(name, population) {
this.countryName = name;
this.countryPopulation = population;
};
ko.applyBindings(new ViewModel("", ""));
所以我需要这段代码来更新在 html 中显示新值的绑定。但这并没有发生,我不确定为什么..
我以为这行 this.loginResult = ko.observable(");应该确保该值是"双向绑定",但似乎不是。有人知道为什么这不更新吗?
其 html 标记如下所示:
<p><span data-bind="value: loginResult"> </span></p>
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var response = xmlhttp.responseXML;
this.loginResult = "Logged In To RNS Successfully";
} else {
// wait for the call to complete
}
好的 - 我解决了这个问题..解决方案是稍微重构代码。
首先将变量预先声明为可观察变量
// Do an asynchronous request to a rest service
this.loginResult = ko.observable('');
var url = 'someurl';
then refactor the method and pass in the variable so that its defined.
runAsyncRequest(url, this.loginResult);
function runAsyncRequest(url, loginResult) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', url, true, 'user', 'pass');
xmlhttp.send(null);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var response = xmlhttp.responseXML;
loginResult('Logged In To RNS Successfully');
} else {
// wait for the call to complete
}
};
}
然后,一切都顺利进行,绑定也会更新。
要在可观察量中设置值,请使用
this.loginResult("Logged In To RNS Successfully");
如果没有括号,您将字符串变量分配给 loginResult,而不是用数据填充它。
来自有关可观察量的文档:(http://knockoutjs.com/documentation/observables.html)
要将新值写入可观察量,请调用可观察量并传递 作为参数的新值。例如,调用 myViewModel.personName('Mary') 会将名称值更改为 'Mary'。