javascriptfancytree

change node icon using fancytree.js


I am using fancytree.js for treeview and I have a callback on the tree:

$("#tree").fancytree({ 
    source: {url: "/" + appPath + "/pathosadmin?treepages=true"},
    postProcess: function (event, data) {
        data.result = convertData(data.response, true);
    },
    init: function (event, data) {
        var root = $("#tree").fancytree("getRootNode");
        root.sortChildren(function (a, b) {
            return treeSort(a, b);
        }, true);
    },
    icon: function (event, data) {

        switch (data.node.data.NODE_TYPE) {
            case 1: //page
                if (data.node.data.STARTPAGE == 0) {
                    return "fancytree_page_icon";
                } else if (data.node.data.STARTPAGE == 1) {
                    _this.startPageNode = data.node;
                    return "fancytree_startpage_icon";
                }
            case 2: //group
                return "fancytree_group_icon";
            case 3: //level
                if (data.node.data.LEVELID) {
                    switch (data.node.data.LEVELID) {
                        case 1:
                            return "fancytree_level_1_icon";
                        case 2:
                            return "fancytree_level_2_icon";
                        case 3:
                            return "fancytree_level_3_icon";
                        case 4:
                            return "fancytree_level_4_icon";
                        case 5:
                            return "fancytree_level_5_icon";
                    }
                } else {
                    return "fancytree_location_icon";
                }
        }
    },
    extensions:

Now I want to also change the icons on runtime. Sadly

if (_this.startPageNode) {
     _this.startPageNode.icon = "fancytree_page_icon";
     _this.startPageNode.renderTitle();
 }
 activeNode.icon = "fancytree_startpage_icon";
 activeNode.render();
 _this.startPageNode = activeNode;

doesnt work. Any hints on how to tackle that problem. The node.icon attribute is always undefined and even if i set it (+render the node) it doesnt show.


Solution

  • renderTitle() calls icon function, so only way I found to change icon dynamically is to put some attribute on node

    activeNode.state = 'clicked';
    activeNode.renderTitle();
    

    and then put extra handling login in icon function on tree:

    var state = data.node.state;
    if (state) {
        switch (state) {
            case "clicked": return "glyphicon glyphicon-ban-circle"
                return;
            case "completed": return "glyphicon glyphicon-ok-circle"
                return;
            case "removed": return "glyphicon glyphicon-remove-circle"
                return;
            default:
                return "glyphicon glyphicon-remove-circle"
                break;
        }
    }