tbonejenkins
tbonejenkins

Reputation: 379

Computed observable not updating value

I'm currently learning how to incorporate knockoutJS in my projects, however, I've run into an issue which has left me stumped.

I have a simple computed observable that returns the value of two concatenated strings. The issue I'm having is that the method returns the correct value when the view first loads, however, if I update one of the observables used in my function, the updated value is not displayed.

index.cshtml

@model KnockoutProjectt.Models.Register

<input type="text" data-bind="value: forename" />
<p data-bind="text: forename"></p>
<p data-bind="text: getFullName"></p>

@section Script {
  <script src="~/Scripts/scripts.js"></script>
  <script>

  var options = {
      forename: '@Html.Raw(Model.Forename)',
      surname: '@Html.Raw(Model.Surname)',
      email: '@Html.Raw(Model.Email)'
  };

  var viewModel = init(options);
  ko.applyBindings(viewModel);

  </script>
}

scripts.js

function init(options) {

  var viewModel = {
      forename: ko.observable(options.forename),
      surname: ko.observable(options.surname),
      email: ko.observable(options.email)
  }

  viewModel.getFullName = ko.computed(function () {
      return options.forename + ' ' + options.surname;
  });

  return viewModel;
}

Any help would be greatly appreciated.

Upvotes: 0

Views: 350

Answers (1)

James Thorpe
James Thorpe

Reputation: 32192

The issue is that the computed is based on the original values passed in on the options object, rather than the observables created from them. You just need to update it to work from the observables:

viewModel.getFullName = ko.computed(function () {
    return viewModel.forename() + ' ' + viewModel.surname();
});

Upvotes: 1

Related Questions