Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout Visible Binding Style Display Inline not working

I am using the visible binding in knockout. I want to set the h3 html element to display:inline. However, after the binding occurs the inline css display: inline is cleared and it reverts back. When I do not use the visible binding then I don't have the issue.

<div style='display: inline'>
    <label style='display: inline'>Product Total</label>
</div>
<div style='display: inline'>
    <h3 style='display: inline' data-bind='visible: Total() > 3, text: Total'></h3>
</div>

Enter a value above 3 to reproduce the issue: http://jsfiddle.net/ryandxavier/ung4z/

like image 889
Ryand.Johnson Avatar asked Feb 20 '14 16:02

Ryand.Johnson


1 Answers

The visible binding togles the visibility of the element between "" and "none", so you need to create a custom binding which support the the inline display:

Based on the visible source code (you can further extend this passing in the desiered display value as a parameter):

ko.bindingHandlers['visibleInline'] = {
    'update': function (element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        var isCurrentlyVisible = !(element.style.display == "none");
        if (value && !isCurrentlyVisible)
            element.style.display = "inline";
        else if ((!value) && isCurrentlyVisible)
            element.style.display = "none";
    }
};

And use in the your html:

<h3 style='display: inline' data-bind='visibleInline: Total() > 3, text: Total'></h3>

Demo JSFiddle.

Or as an alternative solution your can use the container-less syntax and don't put the binding on your h3 and use if instead of visible:

<h3 style='display: inline'>
    <!-- ko if: Total() > 3 -->
        <!-- ko text: Total --><!-- /ko -->
    <!-- /ko -->
</h3>

Demo JSFiddle.

like image 52
nemesv Avatar answered Nov 10 '22 06:11

nemesv