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

时间:2019-05-12 21:41:29

标签: knockout.js knockout-2.0

我有以下内容:

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跟不上。为什么会这样?

1 个答案:

答案 0 :(得分:2)

计算在确定其依赖性方面非常聪明。例如:

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",它都会提早返回而不会调用selectedItem