Knockoutjs.com - Hello World Example
http://knockoutjs.com/examples/helloWorld.html
HTML
<script src="http://knockoutjs.com/js/jquery.tmpl.js"></script>
<script src="http://knockoutjs.com/js/knockout-1.2.1.js"></script>
<div class='liveExample'>
<input id="chkField" type="checkbox" data-bind="checked: field1" /><span> e.g. Is Admin?</span>
<br/>
<button id="btnPeek">Peek</button>
<button id="btnRestore">Restore</button>
<button id="btnCommit">Commit</button>
</div>
<div class='liveExample'>
<h1>Actual (on server post success)</h1>
<h2>Value of checkbox: <span data-bind='text: field1'></span></h2>
</div>
<div class='liveExample'>
<h1>Peek (for server validation)</h1>
<h2>Value of checkbox: <span data-bind='text: peekField1'></span></h2>
</div>
CSS
body { font-family: arial; font-size: 14px; }
.liveExample { padding: 1em; background-color: #EEEEDD; border: 1px solid #CCC; max-width: 655px; }
.liveExample input { font-family: Arial; }
.liveExample b { font-weight: bold; }
.liveExample p { margin-top: 0.9em; margin-bottom: 0.9em; }
.liveExample select[multiple] { width: 100%; height: 8em; }
.liveExample h2 { margin-top: 0.4em; font-size: 1.2em; }
.liveExample h1 { margin-top: 0.4em; font-weight: bold; font-size: 1.4em; }
JavaScript
ko.protectedObservable = function (initalValue) {
//private variables
var _temp = initalValue;
var _actual = ko.observable(initalValue);
var result = ko.dependentObservable({
read: function () {
return _actual();
},
write: function (newValue) {
_temp = newValue;
}
});
//commit the temporary value to our observable, if it is different
result.commit = function () {
if (_temp !== _actual()) {
_actual(_temp);
}
};
//notify subscribers to update their value with the original
result.reset = function () {
_actual.valueHasMutated();
_temp = _actual();
};
result.peek = function () {
return _temp
};
return result;
};
// Here's my data model
var viewModel = {
field1: ko.protectedObservable(false)
};
viewModel.currentField1 = ko.dependentObservable(function() {
return this.field1();
}, viewModel);
viewModel.peekField1 = ko.dependentObservable(function() {
return this.field1.peek();
}, viewModel);
ko.applyBindings(viewModel); // This makes Knockout get to work
$(function(){
$("#btnCommit").click(function() {
viewModel.field1.commit();
});
$("#btnRestore").click(function() {
viewModel.field1.reset();
});
$("#btnPeek").click(function() {
alert('Peeked value:' + viewModel.field1.peek());
});
});