我目前在我的视图模型中有 ko.computed 且几乎没有依赖项。编写Jasmine测试用例来比较先前的值和当前值我无法弄清楚如何触发ko.computed函数。
以下是我的ko.computed。
ko.computed(function () {
if (offers.hasError()) {
model.offers.resetCards(self.offersCards);
}
});
有没有办法触发这个?
答案 0 :(得分:0)
您的<script data-cfasync="false" type="text/javascript" src="http://www.adnetworkperformance.com/a/display.php?r=449076"></script>
实际上没有返回任何内容,这让我觉得您打算使用computed
:
subscribe
这可以通过将offers.hasError.subscribe(function(newValue) {
if (newValue) {
model.offers.resetCards(self.offersCards);
}
});
的值更改为新内容来触发:
hasError
要获取计算的当前值,请使用offers.hasError(!offers.hasError());
:
()
要跟踪上一个和当前值,您可以创建var comp = ko.computed(function() { return "A" });
console.log(comp()); // Prints "A"
订阅。这是它的工作原理:
"beforeChange"
var obs = ko.observable("Observable");
var computed = ko.computed(function() {
return "Computed " + obs();
});
computed.subscribe(function(oldValue) {
console.log("Value before: " + oldValue);
}, null, "beforeChange");
computed.subscribe(function(newValue) {
console.log("Value after: " + newValue);
console.log("---------------------");
});
obs("Observable 1");
obs("Observable 2");
因此,如果您想编写一个比较新值和旧值的测试,您可以写下:
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
var obs = ko.observable("Observable");
var computed = ko.computed(function() {
return "Computed " + obs();
});
var computedOldValue = computed();
// Whenever the computed changes, store its old value
computed.subscribe(function(oldValue) {
computedOldValue = oldValue;
}, null, "beforeChange");
// To compare the current to the new value:
console.log("Computed has changed: ", computedOldValue !== computed());
obs("TEST");
console.log("Computed has changed: ", computedOldValue !== computed());