1
votes

I am using Knockout with MVC Core web application. In my UI I have several input text fields. For example FirstName, LastName and FullName.

I am making FullName as computed observable. Here is my problem. Case 1: Based upon certain condition I want to use the FirstName and LastName data to compute the FullName. (That is the usual case shown in examples).

Case 2: Based upon certain condition I want to read the input that user can enter in the FullName text field. Can someone help me how can I do achieve that.

  function AppViewModel() {
this.firstName = ko.observable('Bob');
this.lastName = ko.observable('Smith');

if(somecondition)
this.fullName = ko.computed(function() {
    return this.firstName() + " " + this.lastName();
} else {
    return somevalueEnterned in the text box

}, this); }

1

1 Answers

1
votes

There's no reason you can't put your logic into the computed itself. Use a separate observable for the text box binding, and then return one or the other depending on your condition.

function AppViewModel() {
  this.firstName = ko.observable('Bob');
  this.lastName = ko.observable('Smith');
  this.textBoxValue = ko.observable('');

  this.fullName = ko.computed(function() {
    if(somecondition)
      return this.firstName() + " " + this.lastName();
    } else {
      return this.textBoxValue();
    }
  }, this);

}