0

在下面的小提琴中:http: //jsfiddle.net/Xa9ez/

有一个名为 jsonData 的变量,它使用 KO 函数 toJSON。

为什么更新其他变量时它不更新?或者甚至在调用 goCaps 函数时?

脚本:

function AppViewModel() {

    this.firstName = ko.observable("Bert");
    this.lastName = ko.observable("Bertington");

    this.fullName = ko.computed(function() {
        return this.firstName() + " " + this.lastName();    
    }, this);

    this.capitalizeLastName = function() {
        var currentVal = this.lastName();        // Read the current value
        this.lastName(currentVal.toUpperCase());

        this.data = ko.toJSON(this);

    };    
    this.data = ko.toJSON(this);
}
var appViewModel = new AppViewModel()
// Activates knockout.js


ko.applyBindings(appViewModel );

html

<p>Last name: <strong data-bind="text: lastName"></strong></p>

<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>

<p>Full name: <strong data-bind="text: fullName"></strong></p>

<button data-bind="click: capitalizeLastName">Go caps</button>
<p>JSON: <strong data-bind="text: data"></strong></p>
​
4

1 回答 1

1

你必须使this.dataobservable:

function AppViewModel() {

    this.firstName = ko.observable("Bert");
    this.lastName = ko.observable("Bertington");

    this.fullName = ko.computed(function() {
        return this.firstName() + " " + this.lastName();    
    }, this);

    this.capitalizeLastName = function() {
        var currentVal = this.lastName();        // Read the current value
        this.lastName(currentVal.toUpperCase());

        this.data(ko.toJSON(this));

    };    
    this.data = ko.observable(ko.toJSON(this));
}

更多关于 observables的信息。

于 2012-10-03T15:54:55.720 回答