我有一个侧边栏索引菜单,它是一个复杂的嵌套树。这是使用TreeNode数据结构创建的,如下所示:
function TreeNode(data){
var self = this;
self.key = ko.observable(data.key);
self.label = ko.observable(data.label);
self.children = ko.observableArray([]);
self.documentPropertyClassId = ko.observable(data.document_property_class_id);
// Recursively create new children
$.each(data.children, function(index, child){
self.children.push(new TreeNode(child));
});
self.isFilterable = ko.pureComputed(function(){
// If a node has no children, then it's a filterable
return !ko.utils.unwrapObservable(self.children).length;
});
}
这是从Ajax请求创建的:
var response = getData(label, id);
response.then(function(data){
self.treeNode(new TreeNode(data, self));
});
这会产生一个像这样的列表,但实际上并没有(我从其他地方复制了链接)http://jsbin.com/Awipoku/13/edit?html,css,js,output
我所挣扎的是递归搜索Tree以寻找包含匹配的documentPropertyClassId的节点。
这是我在互联网上发现的,我正在努力适应Knockout Js领域:
function searchTree(element, matchingTitle){
if(element.title == matchingTitle){
return element;
}else if (element.children != null){
var i;
var result = null;
for(i=0; result == null && i < element.children.length; i++){
result = searchTree(element.children[i], matchingTitle);
}
return result;
}
return null;
}
这是我到目前为止所做的:
function searchTree(node, matchingPropertyId){
if(node.documentPropertyClassId() == matchingPropertyId) {
console.log("found");
return node;
} else if (ko.utils.unwrapObservable(node.children).length > 0) {
var result = null;
console.log("hello");
ko.utils.arrayForEach(node.children(), function(child) {
console.log(child.label());
result = searchTree(child.children, matchingPropertyId);
});
return result;
}
return null;
}