Lets enhance the last example by adding search functionality. We need a function that will return the matching nodes as an array.
The following function does that for us. Add it to the timeline.
[cc lang=”actionscript3″]function isMatch (s, s2) {
return s == undefined ? false : s.toLowerCase ().indexOf (s2) != -1;
}
_global.searchNodes = function (searchString:String, x:XMLNode, includeNodeName:Boolean, includeAttributes:Boolean, includeText:Boolean, arr) {
if (arr == undefined) {
arr = [];
searchString = searchString.toLowerCase ();
if (includeNodeName == undefined) {
includeNodeName = true;
}
if (includeAttributes == undefined) {
includeAttributes = true;
}
if (includeText == undefined) {
includeText = true;
}
}
if (x.nodeType == 1) {
if (includeNodeName && isMatch (x.nodeName, searchString)) {
arr.push (x);
} else if (includeAttributes) {
for (var s in x.attributes) {
if (isMatch (s, searchString)) {
arr.push (x);
break;
}
}
}
for (var i = 0; i < x.childNodes.length; i++) {
arguments.callee (searchString, x.childNodes[i], includeNodeName, includeAttributes, includeText, arr);
}
} else if (includeText && isMatch (x.nodeValue, searchString)) {
arr.push (x);
}
return arr;
};
[/cc]
Add 1 textInput, 1 button, 3 check boxes, and 1 label component as shown below. Name them find_txt, find_pb, names_chk, attrib_chk, text_chk and result_txt respectively.
then add the following code to timeline which makes use of the array returned by the above function to one by one highlight the nodes in the tree
[cc lang=”actionscript3″]
function clearSearch () {
lastKeyword = “”;
}
var searchArr:
Array = [], searchIndex:
Number = 0, lastKeyword:
String;
function treeSearch () {
if (find_txt.
text != lastKeyword) {
lastKeyword = find_txt.
text;
searchIndex = 0;
searchArr = searchNodes (lastKeyword, tree.dataProvider, names_chk.selected, attrib_chk.selected, text_chk.selected);
}
if (searchArr.
length > 0) {
//selected node
if (searchIndex >= searchArr.
length) {
searchIndex = 0;
}
var s = searchArr[searchIndex];
var p = s.parentNode;
while (p !=
undefined) {
tree.
setIsOpen (p,
true,
false);
p = p.parentNode;
}
tree.selectedNode = s;
tree.setFirstVisibleNode (s);
searchIndex++;
result_txt.
text = “
result ” + searchIndex + “
of ” + searchArr.
length;
}
else {
result_txt.
text = “
0 result“;
}
}
[/cc]
We need to do to trigger the functions through button click, so add the following code to the find_pb button
on (click) {
_parent.treeSearch ();
}
When ever the checkboxes are clicked we need to clear the search results and start searching again, so add the following code to all the three check boxes
[cc lang=”actionscript3″]
on (click) {
_parent.clearSearch ();
}
[/cc]
You will get the following result 🙂