这是一个“非”绑定,可用于任何单参数“布尔”类型的绑定,例如checked
, visible
,enable
等。
像这样使用绑定:
<input type="checkbox" data-bind="not: {checked: isVisible}" />
not
绑定:
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);
}
};
我还没有真正尝试过完善绑定,但它似乎功能齐全。
见小提琴