Paul Grimshaw
Paul Grimshaw

Reputation: 21034

Simple Knockout Viewmodel Issue

I have a simple knockout viewmodel problem, which is driving me round in circles... the siteId property binds the first time, but doesn't update on click:

Anyone see what's wrong with this?

function NewSiteAccessViewModel() {
    var self = this;
    self.siteId = ko.observable();
}

$(document).ready(function () {
    var newSiteAccessViewModel = new NewSiteAccessViewModel();


    newSiteAccessViewModel.siteId = 'none yet';

    ko.applyBindings(newSiteAccessViewModel);

    $(".testClick").click(function() {
        newSiteAccessViewModel.siteId = "a new one";
        alert(newSiteAccessViewModel.siteId);
    });
});

HTML:

<h3 data-bind="text:siteId" ></h3>

So the result I get changes the value to "none yet", but doesn't subsequently update on click. The alert shows the new value...

Upvotes: 1

Views: 60

Answers (2)

JohnnyHK
JohnnyHK

Reputation: 311865

For Knockout's view model bindings to update, you must do two things:

  1. The field in the view model must be created using ko.observable().
  2. The field must be set or updated by calling it instead of setting it directly.

So in this case:

  1. siteId must be created in the view model as this.siteId = ko.observable();
  2. siteId must be initialized as newSiteAccessViewModel.siteId('none yet');
  3. siteId must be updated as newSiteAccessViewModel.siteId('a new one');

Upvotes: 2

Matthew James Davis
Matthew James Davis

Reputation: 12295

You set the value of an observable by invoking the observable function. So where you wrote:

newSiteAccessViewModel.siteId = 'none yet';

you want

newSiteAccessViewModel.siteId('none yet');

and similarly from within the click handler.

Upvotes: 2

Related Questions