Henrik
Henrik

Reputation: 2229

jstree triggering the sort plugin

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;
        }
});

But ran into trouble when I allowed the user to dynamicly add elements.

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:

  1. I need to add a new child node
  2. If this requires the parent to move from the "group" that has no children to the group that has, it should be sorted properly.

Upvotes: 2

Views: 5555

Answers (1)

Adam Jimenez
Adam Jimenez

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

Related Questions