Without context around the code, itβs not clear how you are going to use this control. With a checkbox, you usually use the checked binding, which is bound to a logical observable:
A validated binding associates a controlled form element β that is, a check box () or a switch () βto a property in your view model.
So another way of writing using checked bindings:
Code example:
var VM = function () { var self = this; self.myCheck = ko.observable(false); self.myCheck.subscribe(function () { alert('checked value = ' + self.myCheck()); }); } ko.applyBindings(new VM());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> <div> <input type="checkbox" data-bind="checked: myCheck" /> Click me </div>
In this example, an observable is observed that tracks the value of the flag: self.myCheck . Therefore, when the checkbox is checked / self.myCheck() , self.myCheck() will be set to true / false.
In order to provide some output or run some code when the value changes, I subscribed to the observable, which basically means that every time the value of the observable changes, a warning will be displayed (or some code you place there).
source share