我有以下内容:
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
跟不上。为什么会这样?
答案 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
。