Visibility style binding using knockout.js fails

css, javascript, jquery, knockout.js, visibility

Solution

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()"

Problem

``` 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.

Original source