0

我使用 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
    }
};

}

然后一切顺利,绑定更新。

4

1 回答 1

1

要在 observable 中设置值,请使用

this.loginResult("Logged In To RNS Successfully");

如果没有括号,您将一个字符串变量分配给 loginResult,而不是用数据填充它。

从可观察的文档:(http://knockoutjs.com/documentation/observables.html)

要将新值写入可观察对象,请调用可观察对象并将新值作为参数传递。例如,调用 myViewModel.personName('Mary') 会将名称值更改为 'Mary'。

于 2012-11-28T11:48:19.723 回答