尽管可观察到变化,但计算出的可观察不触发

Computed observable not firing despite observable changing

我有以下内容:

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

我预计 selectedItem 的变化会触发这个:

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

但事实并非如此。我看到 self.selectedItem 更新,但 showCreateButton 没有跟进。这是为什么?

计算机在确定它们的依赖关系方面非常聪明。例如:

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>

因为当 exitEarly 仍然是 true 时,代码永远不会到达调用 myObs 的位置,不会创建订阅。只有到达 || 的第二部分后,我们才会开始触发更新 myObs.

的新值

因此,这段代码:

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

根据定义,不能创建对selectedItem的订阅。

每当 sideBarItemType === "Test" 时,它会提前 return 而不会调用 selectedItem