How can I tell if jsTree has fully loaded?

PlTaylor picture PlTaylor · Jul 12, 2012 · Viewed 36.7k times · Source

I am trying to write a function that opens specific nodes on a jsTree but I am having a problem where the function is executed before my base tree is loaded from the ajax call. How can I tell if my jstree data has been loaded and wait until it is done loading. Below is the function I am trying to use.

function openNodes(tree, nodes) {
    for (i in nodes) {
        $('#navigation').jstree("open_node", $(nodes[i]));
    }
}

I am loading my initial tree with the following command

$("#navigation").jstree({
    "json_data": {
        "ajax": {
            "url": function(node) {
                var url;
                if (node == -1) {
                    url = "@Url.Action("BaseTreeItems", "Part")";
                } else {
                    url = node.attr('ajax');
                }
                return url;
            },
            "dataType": "text json",
            "contentType": "application/json charset=utf-8",
            "data": function(n) { return { id: n.attr ? n.attr("id") : 0, ajax: n.attr ? n.attr("ajax") : 0 }; },
            "success": function() {
            }
        }
    },
    "themes": { "theme": "classic" },
    "plugins": ["themes", "json_data", "ui"]
});

Answer

craftsman picture craftsman · Jul 12, 2012

Before you call .jstree() on an element, you can bind your callbacks to before.jstree and loaded.jstree events:

$(selector)
.bind('before.jstree', function(e, data) {
    // invoked before jstree starts loading
})
.bind('loaded.jstree', function(e, data) {
    // invoked after jstree has loaded
    $(this).jstree("open_node", $(nodes[i]));
})
.jstree( ... )