【发布时间】:2016-09-29 05:17:06
【问题描述】:
在我的 ViewModel 中,我有以下属性:
logisticsDestinations: KnockoutObservableArray<Destination>;
filteredlogisticsDestinations: KnockoutComputed<Destination[]>;
logisticsDestinationsFilter: KnockoutObservable<string>;
showNotAddressable: KnockoutObservable<boolean>;
在我的构造函数中,我这样实例化:
//Data from back-end, this works
self.logisticsDestinations = ko.observableArray<Destination>(lines);
self.showNotAddressable = ko.observable<boolean>(true);
self.logisticsDestinationsFilter = ko.observable<string>("");
self.filteredlogisticsDestinations = ko.computed(() => {
//subscribe to properties
//self.showNotAddressable();
var result = self.logisticsDestinations();
if (self.logisticsDestinationsFilter().length > 0) {
return ko.utils.arrayFilter(self.logisticsDestinations(),
item => (item.name.peek()
.toLocaleUpperCase()
.indexOf(self.logisticsDestinationsFilter.peek().toLocaleUpperCase()) >=
0));
}
if (!self.showNotAddressable.peek()) {
result = ko.utils.arrayFilter(result, item => (item.isAddressable.peek()));
}
return result;
}).extend({ paging: '10', rateLimit: 500 });
现在,当我在 logisticsDestinationsFilter 中填写文本时,我的 filteredlogisticsDestinations 会被计算出来。但是,当我检查 showNotAddressable 时,它不会被计算出来。
我可以通过在计算中首先调用self.showNotAddressable(); 来使其工作。但这似乎不是一种好的工作方式,为什么它适用于过滤器而不适用于 Addressable?
有什么想法、建议吗?
谢谢! 托马斯
【问题讨论】:
-
你导致了这个,explicitly,使用
peek? -
KO 通过调用计算函数并检查其读取的内容来跟踪
computed中使用的 observable,尝试在第一个 if 之前将self.showNotAddressalbe()移动到变量,以便 KO 可以看到您正在从两者中获取值logisticDestinationFilter 和 showNotAddressable 可观察对象 -
那么如何在不使用 peek 的情况下获得实际值?如果我先把它放在一个 var 中,不幸的是它不起作用:
var showNotAddressable = self.showNotAddressable; if (!showNotAddressable.peek()) {....
标签: knockout.js typescript observable