knockout.js异步绑定更新

时间:2012-11-28 11:29:53

标签: knockout.js xmlhttprequest

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

}

然后所有人都在游泳,并且更新了绑定。

1 个答案:

答案 0 :(得分:1)

要在observable中设置值,请使用

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

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

来自observables的文档:(http://knockoutjs.com/documentation/observables.html)

  

要为observable写一个新值,请调用observable并传递   新值作为参数。例如,打电话   myViewModel.personName('Mary')会将名称值更改为'Mary'。