Вопрос

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.

Это было полезно?

Решение

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';
}

This worked for me, to make a div be visible only after the page has loaded, using visibility:

<div style="visibility:hidden" data-bind="style: {visibility: 'visible'}">
    ...
</div>
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top