Knockout - Basic

by Pratik Bhattachary

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-debug.js"></script>
<script src="https://code.jquery.com/jquery-2.1.3.js"></script>
<label>Name</label>
<input type="text" data-bind = "value: name, valueUpdate:'afterkeydown'"/>
<input type="checkbox" data-bind = "checked: nameVisible"/> <!--the checked state of the checkbox gets 2 way binded to the boolean value of viewModel object-->
<p>
    Hello, <span data-bind="text: name, visible: nameVisible"></span> <!--Visibility of the span class-->
</p>
<button data-bind = "click: changeName">Change Name</button>

JavaScript

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