Basic Ko Bindings
Demonstrates a basic view model with data binding to the View (UI)
by Randy Crews
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/knockout/3.0.0/knockout-min.js"></script>
<h2>Basic Binding Example</h2>
<p>Binding to tag</p>
<span class="smallText" data-bind="text: generalMessage"></span>
<hr/>
<p>Binding to textbox</p>
<input class="smallText containerWidth" type="text" data-bind="value: generalMessage" />
<hr/>
<p>Binding to a select menu</p>
<select data-bind="options: musicList, optionsText: 'bandName', value: 'musicStyle', optionsCaption: '--Select a Band--' "></select>
<hr/>
CSS
body {
font-family:Arial;
}
.smallText {
font-size: .8em;
font-style: italic;
}
.containerWidth {
width:50%;
}
JavaScript
//basic KO viewmodel
/* note about self (scope)
Using a function to define the view model allows us to have instant access to the data returned to the VM. If we declared the VM as an object literal the data would not be immediately evaluated on instantiation and as a result we would have to write additional code to return the value and types. It is personal preference on the pattern to use but for certain functions such as observables a function is the better approach.
Using 'this' allows us to set the scope of the variable to the current item being selected or called upon */
function myviewmodel() {
var self = this;
//using a static property
self.generalMessage = 'Value bound to view';
//using as static array
self.musicList = [{
bandName: 'AC DC',
musicStyle: 'Rock'
}, {
bandName: 'Blackberry Smoke',
musicStyle: 'Southern Rock'
}, {
bandName: 'FFDP',
musicStyle: 'Metal'
}, {
bandName: 'Rebel Son',
musicStyle: 'Southern Rock'
}];
//working with observables
//-----------------------------------
//using a KO.Observable
//self.generalMessage: ko.observable('ko observable bound to view')
};
ko.applyBindings(new myviewmodel());