Reputation: 2229
After having found a "feature" in jstree, I have now spent most of a day trying to find out how to trigger the sort plugin in jstree.
I am using jstree, and wanted to sort it in a style similar to filesystems, where elements with children are grouped together. (i.e. folders / directories) and elements without children (files) are grouped together, the sort plugin will not always work as expected.
To do this I added the following to the tree construction:
$(jQueryIdString).jstree({
'core': { check_callback: true },
"plugins": ["search", "sort"],
'sort': function (a, b) {
var nodeA = this.get_node(a);
var nodeB = this.get_node(b);
var lengthA = nodeA.children.length;
var lengthB = nodeB.children.length;
if ((lengthA == 0 && lengthB == 0) || (lengthA > 0 && lengthB > 0))
return this.get_text(a).toLowerCase() > this.get_text(b).toLowerCase() ? 1 : -1;
else
return lengthA > lengthB ? -1 : 1;
}
});
The case is that the last element you add is a "folder", but is has no children yet so it is sorted alphabetically, and then you add a "file" in that folder. - but this does not re-sort the parent, as jstree sorting doesn't realise that children may affect parents??
to fix this without redesigning how to build the tree, I ended up using something like this code (that I am not happy about):
var selector = '#treeId';
var root = $(selector).jstree(true).get_node("root_anchor")
var dummyNode = $(selector).jstree(true).create_node(root, "sorting dummy node");
$(selector).jstree(true).delete_node(dummyNode);
I have not yet determined if you would need to do this for all children (that has children)
If anybody has found a better way to do this, I would much appreciate it.
In case you see the API, youll notice that there is a method:
.is_parent(node)
that could be used instead of children.length.
but it does not solve my problem. I started out with that, but then started to inspect the children, and found out that infact there was no children at the time of sorting..
I will not be using the types plugin, unless I have to! This is not actually a filesystem!
**How should I have done this? **
Requirements:
Upvotes: 2
Views: 5555
Reputation: 3145
To trigger a sort you should be able to do:
$(selector).jstree(true).sort(root, true);
$(selector).jstree(true).redraw_node(root, true);
Upvotes: 1