I have a js code at my page that gets JSON-hierarchy from server with separate load and builds a visual Fancytree hierarchy at page (i left html page parts out from example).
$(function() {
$("#tree").fancytree({
source: {
url: '/products/ftree/?format=json',
cache: false,
datatype: 'json',
},
checkbox: false,
})
sortProducts();
console.log('sorted');
});
function sortProducts(){
console.log('in sortProducts()');
var tree = $("#tree").fancytree("getTree");
tree.rootNode.sortChildren(null, true);
tree.visit( function(node) {
node.sortChildren(null, false);
return true;
});
tree.render(true, true);
console.log('end of sort func');
}
.
.
.
<div id='tree' ></div>
each node has titles like
1 Fooo
2 Bar
3 FoooBar
3-1 BarFooo
3-1-1 foofoofoo
3-1-2 barbarbar
4 Buuu
4-1 BuuuBooo
4-1-1 bubobubub
and so on. Page loads fine, it renders the tree correctly and mostly the nodes are in correct order, but at deeper parts 4-2 comes before 4-1 and so on. So I tried to sort them with .sortChildren(null, true) and whatever, but it doesn't sort them. I got the code into shape that it doesn't give any errors and prints debugs just fine, but tree doesn't sort correctly.
Note that code snippet has two attempts, trough rootNode and node traverse, I've tried both alone and together and get the same partially unsorted tree. In my understanding, sortChildren() should sort title-strings without overriding the default cmp function.
Any idea what's wrong with that?
This code is ok
var node = $("#tree").fancytree("getRootNode");
node.sortChildren(null, true);
but the problem is that you try to sort an empty tree, because the asynchronous request has not yet returned.
One solution would be to call it in the init
event:
$("#tree").fancytree({
...
init: function(event, data) {
data.tree.getRootNode().sortChildren(null, true);
},
...