【发布时间】:2012-11-16 05:49:46
【问题描述】:
我在使用 Knockout 的 javascript 视图模型中有这段代码。一切都按设计工作,除了当我的异步调用的回调返回时,我正在努力让两种方式的绑定更新工作。请参阅下面的代码。
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 显示新值的绑定......但这没有发生,我不知道为什么......
我以为这条线 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
}
};
}
然后一切顺利,绑定更新。
【问题讨论】:
-
不幸的是,答案导致 Microsoft JScript 运行时错误:对象不支持属性或方法“loginResult”。所以我假设异步响应在 DOM 上找不到属性?
标签: knockout.js xmlhttprequest