9

I am trying to use computed properties in another computed properties and when i run code i am getting following error in console.

Cannot write a value to a ko.computed unless you specify a 'write' option

function AppViewModel() {
    var self = this; 
    self.firstName = ko.observable('rahul');
    self.lastName = ko.observable('sharma');
    self.fullName = ko.computed(function() {
      return self.firstName() +' ' + self.lastName();
    });
    self.upperFullName = ko.computed(function() {
      return self.fullName.toUpperCase();
    });  
}
// Activates knockout.js
ko.applyBindings(new AppViewModel()); 

and here is html code and js fiddle link

<p><input data-bind="value: firstName"></p>

<p><input data-bind="value: lastName"></p>

<p><input data-bind="value: fullName"></p>

<p> <span data-bind="text: upperFullName"> </span> </p>
4

1 回答 1

9

self.fullName 是一个函数,返回计算值。

self.upperFullName = ko.computed(function() {
  return self.fullName().toUpperCase();
});  

注意括号!

于 2013-10-03T10:31:43.373 回答