0

I have the following:

sidebarCardVm.showCreateButton = ko.computed(function () {
    return
        (sidebarItemType == "Test") ||
        (sidebarItemType == "Test2" && self.selectedItem() != null); // when selectedItem() changes, I expect this to fire.  It does not.
});

I expect a change of selectedItem to trigger this:

self.selectedItem = ko.computed(function () {
    var matchingCard = getSelectedCard("Item")
    if (matchingCard != null && matchingCard.selectedItem() != null)
        return matchingCard.selectedItem();
    return null;
});

But it does not. I see self.selectedItem update, but showCreateButton doesn't follow suit. Why is this?

1 Answer 1

2

Computeds are very smart in determining their dependencies. For example:

const myObs = ko.observable("Hello world");
const returnEarly = ko.observable(true);

const myComp = ko.computed(
  () => returnEarly() || myObs()
);

console.log(myComp()); // true
console.log(myObs.getSubscriptionsCount()); // 0

returnEarly(false);
console.log(myComp()); // "Hello world"
console.log(myObs.getSubscriptionsCount()); // 1
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

Because when exitEarly is still true the code never reaches the point where it calls myObs, no subscription is created. Only once it gets to the second part of the ||, we'll start triggering updates for new values of myObs.

Therefore, this piece of code:

(sidebarItemType == "Test") ||
(sidebarItemType == "Test" && self.selectedItem() != null);

by definition, can not create a subscription to selectedItem.

Whenever sideBarItemType === "Test", it will return early and not call selectedItem.

3
  • So do I just break my conditions into a bunch of if statements with the observable conditions coming first? It doesn't seem smart if it trains humans to expect a certain behavior and then tricks them in an edge-case. May 13, 2019 at 17:33
  • Read the statement from your code I highlighted again. If sidebarItemType is not equal to "Test", the part after && won't be needed to come to the result of false: that's the definition of an AND operator. Only when the a part in a && b is truethy, b will be evaluated. Now, since you've also included an || that checks for a, things break: a || (a && b) will either return a as soon as a is truethy, or return false. It will never return b. May 14, 2019 at 7:12
  • A very important omission was made in my original post. I am testing against a || (b & c) - apologies for the confusion. Either way, I've broken up my computed into if/else statements to force evaluation of the conditions as a workaround. May 14, 2019 at 16:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.