Why is checkbox in knockoutJs written to only when checked?
http://stackoverflow.com/questions/7556689/why-is-checkbox-in-knockoutjs-written-to-only-when-checked
by rniemeyer
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.temp" /><span> e.g. Is Admin?</span>
<br/>
<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: field1.temp'></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 (initialValue) {
//private variables
var _actual = ko.observable(initialValue),
_temp = ko.observable(initialValue);
//access to temp value
_actual.temp = _temp;
//commit the temporary value to our observable, if it is different
_actual.commit = function () {
if (_temp() !== _actual()) {
_actual(_temp());
}
};
//notify subscribers to update their value with the original
_actual.reset = function () {
_actual.valueHasMutated();
_temp(_actual());
};
return _actual;
};
// Here's my data model
var viewModel = {
field1: ko.protectedObservable(false)
};
ko.applyBindings(viewModel); // This makes Knockout get to work
$(function(){
$("#btnCommit").click(function() {
viewModel.field1.commit();
});
$("#btnRestore").click(function() {
viewModel.field1.reset();
});
});