data-bind="style : { display : repeat() === 'Custom' ? 'block' : 'none' }"
This style binding succeeds using knockout where as the following fails
data-bind="style : { visibility : repeat() === 'Custom' ? 'visible' : 'hidden' }"
Why?
I can use visible binding but in my case I don't want to lose that div space even when it is hidden.
How can I achieve this?
I don't want to make this happen using jquery as I have already succeeded using it.
Binding Values The binding value can be a single value, literal, a variable or can be a JavaScript expression.
A binding consists of two items, the binding name and value, separated by a colon. Here is an example of a single, simple binding: Today's message is: <span data-bind= "text: myMessage" ></span> An element can include multiple bindings (related or unrelated), with each binding separated by a comma.
Note: Using “if” and “ifnot” without a container element-- ko --> and <! -- /ko --> comments act as start/end markers, defining a “virtual element” that contains the markup inside. Knockout understands this virtual element syntax and binds as if you had a real container element.
Activating Knockoutko. applyBindings(myViewModel); You can either put the script block at the bottom of your HTML document, or you can put it at the top and wrap the contents in a DOM-ready handler such as jQuery's $ function.
Another option to solve this issue is to create your own binding. That sounds hard, but it's really easy and KO was designed with custom binding in mind. I wish the base package had more of them, but they are trivial to create. The advantage to this solution is that your binding is simple and more legible. Here is an example, called hidden:
ko.bindingHandlers.hidden = (function() {
function setVisibility(element, valueAccessor) {
var hidden = ko.unwrap(valueAccessor());
$(element).css('visibility', hidden ? 'hidden' : 'visible');
}
return { init: setVisibility, update: setVisibility };
})();
And used in your HTML as:
data-bind="hidden: !repeat()"
I just did something very similar and this worked for me:
data-bind="style : { visibility : repeat() === 'Custom' ? '' : 'hidden' }"
The difference is setting visibility
to ''
rather than visible
.
Would probably be better to use the css
binding http://knockoutjs.com/documentation/css-binding.html. You could also tidy the whole thing with a computed
observable.
self.hidden = ko.computed(function() {
return self.repeat() !== 'Custom';
})
Your binding is now this simple data-bind="css: { hide: hidden }"
In your CSS provide the following class:
.hide {
visibility: 'hidden';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With