Ko Observable Bindings

Demonstrates a basic view model with data binding observable objects to the View (UI)

by Randy Crews

HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/knockout/3.0.0/knockout-min.js"></script>
<h2>KO Observable Bindings</h2>

<p>KO binding to tag</p>
<span class="smallText" data-bind="text: generalMessage"></span>

<hr/>
<p>KO binding to textbox</p>
<input class="smallText containerWidth" type="text" data-bind="value: generalMessage" />
<!-- binding to a click event -->
<input type="button" data-bind="click: addValue" value="Add to Array">
<hr/>
<!-- illustrates a foreach loop that updates the DOM when the array is updated -->
<p>My Notes</p>
<ul data-bind="foreach: myNotesArray">
    <li data-bind="text: $data" />
</ul>
<hr/>
<p>KO binding to a select menu</p>
<select data-bind="options: musicList, optionsText: 'bandName', value: selectedBand, optionsCaption: '--Select a Band--' "></select>
<!-- illustrates visibility binding using 'if' binding -->
<span data-bind="if: selectedBand" >This band plays: <span data-bind="text: selectedBand().musicStyle"></span>
</span>
<hr/>

CSS

body {
    font-family:Arial;
}
.smallText {
    font-size: .8em;
    font-style: italic;
}
.containerWidth {
    width:50%;
}

JavaScript

//basic KO viewmodel
function myviewmodel() {
    var self = this;
    //using an observable utilizes notify property changed events
    self.generalMessage = ko.observable('Value bound to view');

    //using as mutlt value array
    self.musicList = ko.observableArray([{
        bandName: 'AC DC',
        musicStyle: 'Rock'
    }, {
        bandName: 'Blackberry Smoke',
        musicStyle: 'Southern Rock'
    }, {
        bandName: 'FFDP',
        musicStyle: 'Metal'
    }, {
        bandName: 'Black Sabbath',
        musicStyle: 'Rock'
    }]);

    //observable to store the selected sytle
    self.selectedBand = ko.observable();

    //empty array
    self.myNotesArray = ko.observableArray([]);

    //button click
    self.addValue = function () {
        self.myNotesArray.push(self.generalMessage()); // here we are evaluating the observable current value
    };



};
ko.applyBindings(new myviewmodel());