问题
Is is possible to implement a "not" binding using Knockout? Basically, I want to negate the binding value, but retain the two-way binding/observability.
In my view model, I have a property, isVisible
, but my UI requirements dictate that I provide a checkbox to represent the hidden, or "not visible" state. I would prefer not to create a duplicate or second property to track the negated state.
Code such as this does not work fully because it does not pass the observable to the binding:
<label>Is Hidden?<input type="checkbox" data-bind="checked: !isVisible()" /></label>
Note: This is a Q&A style question - Although I'm posting an answer, I'm also very interested in any different or improved answers
回答1:
Here's a "not" binding that can be used for any single-parameter "bool" type of binding, such as checked
, visible
, enable
, etc.
Use the binding like this:
<input type="checkbox" data-bind="not: {checked: isVisible}" />
The not
binding:
ko.bindingHandlers.not = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
//expects a single, truthy/falsy binding,
// such as checked, visible, enable, etc.
var binding = valueAccessor();
var observable = binding[Object.keys(binding)[0]];
var notComputed = ko.computed({
read: function () {
return !observable();
},
write: function (newValue) {
observable(!newValue);
}
});
var newBinding = {};
newBinding[Object.keys(binding)[0]] = notComputed;
ko.applyBindingsToNode(element, newBinding, viewModel);
}
};
I haven't really tried to polish the binding, but it seems to be fully functional.
See the Fiddle
来源:https://stackoverflow.com/questions/16368784/how-to-negate-the-isvisible-binding-in-knockout-using-a-generic-not-binding