编辑:添加了populateDropdown函数和函数isSystemCorrect的代码(见下)
编辑2我把它缩小了一点,问题似乎出现在计算的observable中的arrayFilter函数中。无论我尝试什么,这都会返回一个空数组。我已经检查过self.testsuites()在过滤之前看起来没问题,但过滤仍然失败。
我的计算observable,filteredTestsuites有问题。
正如您从screendump中看到的那样,可观察到的testsuites可正确填充,但计算的observable仍为空。我还尝试从下拉菜单中选择“付款”之外的其他选项,看看是否会触发观察,但事实并非如此。
我认为每次改变self.testsuites()或self.dropdownSelected()时都会更新计算的observable,但它似乎都没有触发它们。
我在这里做错了什么?
我只是想让计算出的可观察过滤器在所选择的下拉选项之后进行测试,每次都改变。
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)));
}
答案 0 :(得分:2)
正如评论中所建议的那样 - 重写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。