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

1

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>
Josephinajosephine answered 3/10, 2013 at 10:26 Comment(4)
why use a input when its not a writable computed?Slosh
@Slosh sorry i didnt get you ? i am very much new in knockoutjs .Josephinajosephine
@Slosh 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 ?Josephinajosephine
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 observableSlosh
I
9

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

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

notice the parenthesis!

Indivertible answered 3/10, 2013 at 10:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.