[英]Knockout.js: computed observable not updating as expected
编辑:为函数populateDropdown和函数isSystemCorrect添加了代码(请参见底部)
编辑2我已将其范围缩小了一点,该问题似乎出现在已计算的可观察值的arrayFilter函数中。 无论我尝试什么,这都会返回一个空数组。 我已经检查过self.testsuites()在过滤之前看起来还可以,但是过滤仍然失败。
我的计算得出的可观察的filterTestsuites有问题。
从屏幕转储中可以看到,testsuites observable已正确填充,但是计算出的observable仍然为空。 我还尝试从下拉菜单中选择“付款”以外的其他选项,以查看是否会触发可观察到的选项,但没有触发。
我认为计算的可观察值将在每次self.testsuites()或self.dropdownSelected()更改时进行更新,但似乎都不会触发它们。
我在这里做错了什么?
我只是想在选定的下拉选项之后使测试套件成为计算的可观察的过滤器,每次它们中的任何一个改变。
function ViewModel() {
var self = this;
// The item currently selected from a dropdown menu
self.dropdownSelected = ko.observable("Payment");
// This will contain all testsuites from all dropdown options
self.testsuites = ko.mapping.fromJS('');
// This will contain only testsuites from the chosen dropdown option
self.filteredTestsuites = ko.computed(function () {
return ko.utils.arrayFilter(self.testsuites(), function (testsuite) {
return (isSystemCorrect(testsuite.System(), self.dropdownSelected()));
});
}, self);
// Function for populating the testsuites observableArray
self.cacheTestsuites = function (data) {
self.testsuites(ko.mapping.fromJS(data));
};
self.populateDropdown = function(testsuiteArray) {
for (var i = 0, len = testsuiteArray().length; i < len; ++i) {
var firstNodeInSystem = testsuiteArray()[i].System().split("/")[0];
var allreadyExists = ko.utils.arrayFirst(self.dropdownOptions(), function(option) {
return (option.Name === firstNodeInSystem);
});
if (!allreadyExists) {
self.dropdownOptions.push({ Name: firstNodeInSystem });
}
}
};
}
$(document).ready(function () {
$.getJSON("/api/TestSuites", function (data) {
vm.cacheTestsuites(data);
vm.populateDropdown(vm.testsuites());
ko.applyBindings(vm);
});
}
函数isSystemCorrect:
function isSystemCorrect(system, partialSystem) {
// Check if partialSystem is contained within system. Must be at beginning of system and go
// on to the end or until a "/" character.
return ((system.indexOf(partialSystem) == 0) && (((system[partialSystem.length] == "/")) || (system[partialSystem.length] == null)));
}
如注释中所建议-重写cacheTestsuites方法:
self.testsuites = ko.observableArray();
self.filteredTestsuites = ko.computed(function () {
return ko.utils.arrayFilter(self.testsuites(), function (testsuite) {
return (isSystemCorrect(testsuite.System(), self.dropdownSelected()));
});
});
self.cacheTestsuites = function (data) {
var a = ko.mapping.fromJS(data);
self.testsuites(a());
};
唯一不同的是将observableArray从映射函数中解包。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.