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("", ""));
したがって、this.loginResult の 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
}
};
}
その後、すべてがスムーズに動作し、バインディングが更新されます。