marcus
marcus

Reputation: 333

jsTree fails on second refresh

I'm using a jsTree plugin and found that on the second time I call the refresh(), the tree will remain in an error / loading state. Here is the code:

.on('changed.jstree', function (e, data) {
    var i, j, selectedNode;
    selectedNode = data.node;
    currentlySelectedNodeGUID = selectedNode.id;
    //for (i = 0, j = data.selected.length; i < j; i++) {
    //    selectedNode = data.instance.get_node(data.selected[i]);
    //    currentlySelectedNodeGUID = selectedNode.id;
    //}
    $.ajax({
        url: '@Url.Action("LocationProperties","Location")',
        type: 'GET',
        data: { id: currentlySelectedNodeGUID },
        success: function (result) {
            $('#locationPropertiesPartial').html(result);
        },
        error: function (e) {
            alert(e);
        }
    });
});

The only problem I found was that I get this error Uncaught TypeError: Cannot read property 'id' of undefined at this line currentlySelectedNodeGUID = selectedNode.id;.

The data however is there, the data.node does contain an id property and it does have a value, which gets assigned to currentlySelectedNodeGUID.

I'm pretty much clueless as to why this happens. Any help please?

Upvotes: 1

Views: 1443

Answers (2)

Daniel Caime
Daniel Caime

Reputation: 1

Evaluate whether data.node or data.selected is null before the assignment, when the jstree is refreshed don't take error, and you can refresh any times you need.

if (data.node != null) {
   var dataid = data.node.id;
}

Upvotes: 0

karim
karim

Reputation: 311

When you call refresh() your currently selected node is deselected, which triggers the changed event. When there is no node selected data.node is null (or undefined). That's why data.node.id also is undefined. After the tree has been refreshed the node gets selected again, which triggers changed once again - this time with the node object available.

So you'll need to check if there actually is a node selected before you send that ajax query.

Upvotes: 1

Related Questions