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>
rahularyansharma
  • 10,835
  • 17
  • 74
  • 127
  • why use a input when its not a writable computed? – Anders Oct 03 '13 at 11:38
  • @Anders sorry i didnt get you ? i am very much new in knockoutjs . – rahularyansharma Oct 03 '13 at 12:01
  • @Anders OK got it , you want to say that when there is no calculation on upperFullName why should i use this as computed.Yes you are right . but how can i show then uppercase fullName ? – rahularyansharma Oct 03 '13 at 12:53
  • 1
    No i meant that since you use a input and value binding to bind 'fullName' it indicates that you want to write to the observable, but you use a read only observable – Anders Oct 03 '13 at 13:55

1 Answers1

9

self.fullName is a function, returning the computed value.

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

notice the parenthesis!

lordvlad
  • 4,638
  • 1
  • 19
  • 40