Reputation: 3294
i have an input type checkbox in knockout js and i whant to perform the "not true" action when this checkbox is checked. Something like this:
<input type="checkbox" data-bind="checked: !IsVisible"/>
But this is not working. I know that i can call IsHidden and set the common checked binding, but i have a special situation in witch i need this behavior.
Upvotes: 2
Views: 2033
Reputation: 14697
Define a custom binding. See "Simplifying and cleaning up views in KnockoutJS" which has a section very, very similar to what you're asking for. Basically, something like this should work (NOTE: not tested):
ko.bindingHandlers.notChecked = {
update: function(element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
ko.bindingHandlers.checked.update(element, function() { return!value; });
}
};
Then you could do:
data-bind="notChecked: IsVisible"
Upvotes: 5
Reputation: 8520
You can evaluate the observable directly in the binding, and your idea should work.
like this: <input type="checkbox" data-bind="checked: !IsVisible()"/>
Note, however, this loses the "observability", which is probably not what you want.
An alternative is to create an IsHidden
property that is computed off of IsVisible.
var ViewModel = function (model) {
var self = this;
self.IsVisible = ko.observable(model.IsVisible);
self.IsHidden = ko.computed({
read: function () {
return !self.IsVisible();
},
write: function (newValue) {
self.IsVisible(!newValue);
}
});
}
Upvotes: 3
Reputation: 9167
It's because with ! you're performing a function on the observable. Use this:
<input type="checkbox" data-bind="checked: !IsVisible()"/>
Upvotes: 0