2012-10-03 70 views
0

下面撥弄: http://jsfiddle.net/Xa9ez/淘汰賽JSON沒有更新

有一個叫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> 
​ 
+0

'this.data'似乎不是可觀察的。 –

+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