0

I am dynamically creating buttons in javascript, and each button is supposed to select their corresponding node in a jsTree. The problem is that all the buttons select the last node in their respective branch. The jsTree is working as it is supposed to, so that is not the issue. The relevant code:

        var children = node.children;
        for (var i = 0; i < children.length; i++) {
            var childNode = myTree.get_node(children[i]);
            var myButton = document.createElement("div");

            myButton.className = 'imageButton';

                myButton.onclick = function () {
                    myTree.deselect_all([true]);
                    myTree.select_node(childNode);
                };

When I am building the buttons, the childNode is the correct node.

The problem is when the onClick fires, the childNode is the the last element in children[]. Which is then selected.

Any suggestions?

2 Answers2

0

I think the problem lies in closure. The link explains it very well. Anyway, I'd try this and see what happens:

function clickEvHandlerClosure(childnode) {
    return function () {
        myTree.deselect_all([true]);
        myTree.select_node(childnode);
    };
}

// your code
....

// In the loop, replace this:
//myButton.onclick = function () {
//                myTree.deselect_all([true]);
//                myTree.select_node(childNode);
//            };
// for this:
myButton.onclick = clickEvHandlerClosure(childnode);

Could work.

Community
  • 1
  • 1
acontell
  • 6,792
  • 1
  • 19
  • 32
0

I used the bind function to make it work.

     myButton.onclick = function (index) {
                var myTree = $('#jstree').jstree();
                var node = myTree.get_selected(true)[0];
                var children = node.children;
                var childNode = myTree.get_node(children[index]);
                    myTree.deselect_all([true]);
                    myTree.select_node(childNode);
                }.bind(this, i);