Search code examples
kendo-treeviewdatabound

prevent expanding parent node when its datasource is updated due to addition of a child item inside kendo treeview


I have a kendotreeview with 3 root parent nodes.Example is shown below.
When I drop child3 into New SubGroup, the node "New Subgroup" gets expanded by default even if it was collapsed before. I would like to prevent this possibility. If New SubGroup was expanded before, then I would like to keep it as it is. The problem is that the expand gets called before the databound event and hence I am stuck here.

Please help.

parent1:

--New SubGroup  
--Child2  
--Child3 
--Child4   

parent2:

--Child4  
--Child5  

Code snippet:
 dataBound: function (e) {
            console.log("DataBound", e.node);
            var nodedataitem = $("#DimMeasTree").data("kendoTreeView").dataItem($(e.node));
            if (nodedataitem.FieldKey === "SubGroup" && ($(e.node).attr("aria-expanded")) === "true") {
                
                $("#DimMeasTree").data("kendoTreeView").collapse($(e.node));
           }
        }


Solution

  • I am subscribing to my own custom expand function (i.e. subgroup_expand()) after I initialize my treeview. It is as demonstrated below:

    <div id="treeview"></div>
    <script>
    function subgroup_expand(e) {
       if (typeof event === 'undefined') {
            //If browser is Firefox, the subgroup will expand and do not close automatically.
            // It is because Firefox does not support "event" attribute gloabally as in IE or in Google chrome.
        }
       else if (!!e.node && typeof(event) !== 'undefined' && event.type !== "click" && event.type !== "dblclick") {
            var nodedataitem = $("#treeview").data("kendoTreeView").dataItem($(e.node));
            if (nodedataitem.FieldKey === "SubGroup") {
                // e.preventDefault();
                setTimeout(function () {
                    //Collapse the subgroup if it was not expanded by click or dblclick.
                    $("#treeview").data("kendoTreeView").collapse($(e.node));
                }, 50);
            }
        }
    }
    $("#treeview").kendoTreeView({
      dataSource: modeldata
    });
    var treeview = $("#treeview").data("kendoTreeView");
    treeview.bind("expand", subgroup_expand);
    </script>