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 mon checked binding, but i have a special situation in witch i need this behavior.
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 mon checked binding, but i have a special situation in witch i need this behavior.
Share Improve this question asked May 3, 2013 at 13:15 Phoenix_uyPhoenix_uy 3,30410 gold badges59 silver badges106 bronze badges 1-
For an interesting exercise, I posted a Q&A question that demonstrates a generic "not" binding, which allows you to write the html like this:
<input type="checkbox" data-bind="not: {checked: isVisible}" />
(stackoverflow./q/16368784/91189) – Joseph Gabriel Commented May 3, 2013 at 23:09
3 Answers
Reset to default 5Define 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"
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 puted off of IsVisible.
var ViewModel = function (model) {
var self = this;
self.IsVisible = ko.observable(model.IsVisible);
self.IsHidden = ko.puted({
read: function () {
return !self.IsVisible();
},
write: function (newValue) {
self.IsVisible(!newValue);
}
});
}
See the Fiddle
It's because with ! you're performing a function on the observable. Use this:
<input type="checkbox" data-bind="checked: !IsVisible()"/>