<div data-bind="css: { highlighted: highlight }, click: toggleHighlight">
random string
</div>
<input type="checkbox" data-bind="css: { 'checked': dimitri, 'unchecked': !dimitri() }, click: toggledimitri, checked: dimitri">
var ViewModel = function() {
var self = this;
self.dimitri = ko.observable(false);
self.toggledimitri = function() { self.dimitri(!self.dimitri()) };
self.highlight = ko.observable(true);
self.toggleHighlight = function () { self.highlight(!self.highlight()) };
}
ko.applyBindings(new ViewModel());
var vm = ko.dataFor(document.body);
What basically I'm after is the toggling of css classes {checked and unchecked} whilst also checking and unchecking the checkbox using knockout checked: css: and click: . Any ideas which bit I'm not doing right? jsfiddle
As suggested in the comments, the checked and click will effectively negate each other. The checked binding will automatically toggles while the click manually toggles once more. Removing the click fixes the issue.
<input type="checkbox" data-bind="css: { 'checked': dimitri, 'unchecked': !dimitri() }, checked: dimitri">
Instead of using the css
binding, you can try using the attr
binding and bind directly to the class
attribute. You can use a ko.computed
method to return the appropriate CSS class name. Also, you don't need the click
event as user3297291 stated. The checkbox would look like this:
<input type="checkbox" data-bind="attr: { 'class': checkedClass }, checked: dimitri">
And the ko.computed
method would look like this:
this.checkedClass = ko.computed(function() {
return this.dimitri() ? 'checked' : 'unchecked';
}, this);
Here is a link to the updated fiddle which demonstrates this:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.