Starting point for Knockout Examples
Latest copy of: -jQuery templates -KnockoutJS -KO Mapping plugin
by vbfischer
HTML
<script src="https://github.com/jquery/jquery-tmpl/raw/master/jquery.tmpl.js"></script>
<script src="https://github.com/SteveSanderson/knockout/raw/master/build/output/knockout-latest.debug.js"></script>
<script src="https://github.com/SteveSanderson/knockout.mapping/raw/master/build/output/knockout.mapping-latest.debug.js"></script>
<div class="liveExample">
<select data-bind= 'options: serverOptions,
optionsText: "name", optionsValue: "id", value: theOptionId'></select>
<div class="box">
<h2>Selected Option Info</h2>
<p>Selected OptionId: <span data-bind='text: theOptionId'></span></p>
<p>Selected OptionName: <span data-bind='text: theOptionName'></span></p>
</div>
<div class="box">
<h2>Model Dump (JSON)</h2>
<p><span data-bind='text: ko.toJSON(viewModel)'></span></p>
</div>
</div>
CSS
.liveExample {
padding: 1em;
background-color: #EED;
border: 1px solid #CCC;
max-width: 655px;
}
.liveExample select[multiple] {
width: 100%;
height: 8em;
}
.box {
border: 2px solid black;
margin: 10px;
padding: 10px;
}
h2 { font-size: 1.3em; font-weight:bold;}
JavaScript
//
// This code was taken from Steve Sandersons Knockoutjs.com site.
// http://knockoutjs.com/examples/simpleList.html
//
var serverOptions = [
{id:1,name:"red"},
{id:2,name:"green"},
{id:3,name:"blue"}
];
var viewModel = {
theOptionId: ko.observable(2)
};
viewModel.theOptionName = ko.dependentObservable(function(){
var id = parseInt(this.theOptionId(), 10);
var result = ko.utils.arrayFirst(serverOptions, function(option) {
return option.id === id;
});
return result ? result.name : "NO NAME";
}, viewModel);
ko.applyBindings(viewModel);