JBFB
JBFB

Reputation: 43

Knockout: Toggle table visibility inside foreach div

I have the following basic structure. I need to be able to toggle the visibility of the each table individually. Classes don't seem to work, since it would toggle all with the same class. There are an unknown number of items so there is an unknown number of outer divs and I don't know the id as it isn't unique.

<div data-bind="foreach: items">
    // Other pieces of data here...

    <button data-bind="click: myToggleFunction">Hide/Show</button> // This could be image, link or whatever to trigger toggle
    <table>  // Need to toggle tables individually
        //Rows and columns here bound to the elements of each "item"
    </table>
</div>

Just not sure how to have it determine which table it's trying to toggle.

Upvotes: 2

Views: 3049

Answers (2)

Bardicer
Bardicer

Reputation: 1469

The easiest way I can think of would be to have visibility flags in the viewmodel. In the view, use the knockoutjs "if" binding on the div. (You will need to have the toggle link outside of the div of course).

Something like

 <div data-bind="if: div1Visibility">
     Show this stuff if div1Visibility is true, otherwise don't.
 </div>
 <div data-bind="if: div2Visibility">
     Show this stuff if div2Visibility is true, otherwise don't.
 </div>

You can also do something like:

<!-- ko if: div1Visibility -->
    Show div1 stuff.
<!-- /ko -->
<!--  ko if: div2Visibility  -->
    Show div2 stuff.
<!--  /ko -->

Upvotes: 0

Brigand
Brigand

Reputation: 86220

See a Demo

I like to have a toggle function handy for Knockout projects. Here's one.

ko.observable.fn.toggle = function () {
    var obs = this;
    return function () {
        obs(!obs())
    };
};

We can then create objects with a visible property. Define all of your table data inside these objects.

function Item() {
    var self = this;

    self.visible = ko.observable(true);
}

Our ViewModel contains an array of these items. It's on the fiddle if you need it.

When we get to our HTML, we can set visible.toggle() in our click handler, which toggles our visible observable. Our table is also bound to be visible when our Item's visible property is true.

<div data-bind="foreach: items">
    <div>
        <button data-bind="click: visible.toggle()">Toggle</button>
        <table data-bind="visible: visible">
            ...
        </table>
    </div>
</div>

Upvotes: 6

Related Questions