0
votes

I have a set of checkboxes that control the visibility of a set of items on my page. I'm trying to add some functionality so that when none of the boxes are checked, all of the items show up.

I guess my first question is, can I use a logical operator in my data-bind as I'm doing below? From the documentation here (http://knockoutjs.com/documentation/binding-syntax.html) it seems like I should be able to. I'm trying to avoid having to create an extra set of computeds for all of the checkboxes. If this is possible, what am I doing wrong?

<div data-bind="visible: (showStaff() || showAll())" class="procedure">

When I look in the KnockoutJS inspector in Chrome, it appears as though only "showStaff()" is being evaluated, not the rest of the expression. I have also tried the following since I knew that both showStaff() and showAP() worked. It still only evaluated the first half.

<div data-bind="visible: (showStaff() || showAP())" class="procedure">

Here is my js:

var self = this;
self.showAP = ko.observable(true);
self.showTR = ko.observable(true);
self.showSR = ko.observable(true);
self.showStaff = ko.observable(true);
self.showNSW = ko.observable(true);
self.showGA = ko.observable(true);
self.showP14 = ko.observable(true);
self.showSW = ko.observable(true);
self.showAll = ko.computed(function () {
    var show;
    if (!self.showAP && !self.showTR && !self.showSR && !self.showStaff && !self.showNSW && !self.showGA && !self.showP14 && !self.showSW) {
        showAll = true;
        return show;
    }
    else {
        showAll = false;
        return show;
    }
});
2
If showStaff is true; showAP won't be evaluted. Because true || something give always true. - Damien
I am not sure you need the extra parens jsfiddle.net/GcTCh - BillPull

2 Answers

0
votes

You work with observable in wrong way. Modify your computed as follow:

self.showAll = ko.computed(function () {
    var show;
    if (!self.showAP() && !self.showTR() && !self.showSR() && !self.showStaff() && !self.showNSW() && !self.showGA() && !self.showP14() && !self.showSW()) {
        show = true;
        return show;
    }
    else {
        show = false;
        return show;
    }
});
0
votes

You should add () if you want the value of an observable.

self.showAll = ko.computed(function () {
    var show;
    if (!self.showAP() && !self.showTR() && !self.showSR() && !self.showStaff() && !self.showNSW() && !self.showGA() && !self.showP14() && !self.showSW()) {
        showAll = true;
        return show;
    }
    else {
        showAll = false;
        return show;
    }
});