0
votes

I am new to Knockout and am learning how MVVM works. Here is a code snippet of my code.

$(function () {
  var viewModel = {
    name: ko.observable("Bob"),
    changeName: function () {
      this.name("Steve");
    },
    nameVisible: ko.observable(true);
  };

  ko.applyBindings(viewModel);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-debug.js"></script>

Name:
<input type="text" data-bind="value: name, valueUpdate: 'afterkeydown'" />
<input type="checkbox" data-bind="checked: nameVisible" />
<p>Hello, <span data-bind='text: name, visible: nameVisible'></span>
</p>
<button data-bind='click: changeName'>Change Name</button>

I am attempting to data-bind the View to the ViewModel. The text in the input field should appear when the checkbox is selected. The button should also update the input field to 'Steve' when clicked (only when the checkbox is checked). What is going wrong?

1
Just a small point: you don't need to put your view-model in the $(function... closure. This view-model can be processed while the browser is performing other tasks. However, you'll probably want to keep the applyBindings call in there though. - awj
Noted. Thanks for the tip Carlos! - mbrashid62

1 Answers

2
votes

You have error in your syntax. Should be:

$(function () {
  var viewModel = {
    name: ko.observable("Bob"),
    changeName: function () {
      this.name("Steve");
    },
    nameVisible: ko.observable(true)
  };

  ko.applyBindings(viewModel);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-debug.js"></script>

Name:
<input type="text" data-bind="value: name, valueUpdate: 'afterkeydown'" />
<input type="checkbox" data-bind="checked: nameVisible" />
<p>Hello, <span data-bind='text: name, visible: nameVisible'></span>
</p>
<button data-bind='click: changeName'>Change Name</button>

No semicolon needed after: nameVisible: ko.observable(true)

Always have developer console open for this.