Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 526
rahularyansharma Avatar asked Oct 03 '13 10:10

rahularyansharma


People also ask

What is Ko computed in knockout JS?

ko. computed( evaluator [, targetObject, options] ) — This form supports the most common case of creating a computed observable. evaluator — A function that is used to evaluate the computed observable's current value. targetObject — If given, defines the value of this whenever KO invokes your callback functions.

What is Ko Purecomputed?

Pure computed observables, introduced in Knockout 3.2. 0, provide performance and memory benefits over regular computed observables for most applications. This is because a pure computed observable doesn't maintain subscriptions to its dependencies when it has no subscribers itself.


1 Answers

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

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

notice the parenthesis!

like image 104
lordvlad Avatar answered Oct 26 '22 07:10

lordvlad