Linking the visibility style using the knockout.js function fails

data-bind="style : { display : repeat() === 'Custom' ? 'block' : 'none' }" 

This style binding succeeds using a knockout, where in the event of a failure

 data-bind="style : { visibility : repeat() === 'Custom' ? 'visible' : 'hidden' }" 

Why?

I can use visible binding, but in my case I do not want to lose this div space even when it is hidden.

How can i achieve this?

I do not want this to happen using jquery, since I already managed to use it.

+6
source share
3 answers

Another solution to this problem is to create your own binding. It sounds complicated, but it is very simple, and KO was designed with custom bindings in mind. I want the base package to have more of them, but they are trivial to create. The advantage of this solution is that your binding is simple and straightforward. 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()" 
+11
source

I just did something very similar and it worked for me:

 data-bind="style : { visibility : repeat() === 'Custom' ? '' : 'hidden' }" 

The difference lies in setting visibility to '' , not to visible .

+4
source

It is probably best to use the css binding http://knockoutjs.com/documentation/css-binding.html . You can also tidy it all up with a computed observable.

 self.hidden = ko.computed(function() { return self.repeat() !== 'Custom'; }) 

Now your binding is simple: data-bind="css: { hide: hidden }"

In your CSS, specify the following class:

 .hide { visibility: 'hidden'; } 
+1
source

All Articles