Knockout JSON没有更新

时间:2012-10-03 15:33:17

标签: javascript json knockout.js

在下面的小提琴中: 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>
​

1 个答案:

答案 0 :(得分:1)

你必须让this.data可观察:

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));
}

More about observables