I have a situation that has been bugging me for some time. I have a Kendo UI treeview in my project set up as described on http://demos.telerik.com/kendo-ui/web/treeview/events.html.
What I need to achieve is to say when I expand a node on the treeview, all the other nodes not in this branch should be collapsed and on this branch expanded. I have tried using the following code but unfortunately its going into an infinite loop.
<div id="example" class="k-content">
<div id="treeview" class="demo-section" style="width: 200px"></div>
<div class="demo-section">
<h3 class="title">Console log
</h3>
<div class="console"></div>
</div>
<script type="text/javascript">
$(document).ready(function() {
function onExpand(e) {
e.preventDefault();
kendoTreeView.collapse('.k-item');
kendoTreeView.expand(e.node);
}
$("#treeview").kendoTreeView({
dataSource: [
{ text: "Furniture", expanded: true, items: [
{ text: "Tables & Chairs" },
{ text: "Sofas" },
{ text: "Occasional Furniture" }
] },
{ text: "Decor", items: [
{ text: "Bed Linen" },
{ text: "Curtains & Blinds" },
{ text: "Carpets" }
] },
{ text: "Storage" }
],
expand:OnExpand
});
});
</script>
Please help.
Thanks
As @Logard correctly points out, if you try to expand inside the OnExpand
you will enter an infinite loop since after collapsing other nodes, you want to expand current and this will trigger a new call to OnExpand
.
In order to prevent this, you should define OnExpand
handler as:
function OnExpand(e) {
if (kendoTreeView.collapsingOthers) {
kendoTreeView.collapsingOthers = false;
} else {
kendoTreeView.collapse('.k-item');
kendoTreeView.collapsingOthers = true;
kendoTreeView.expand(e.node);
}
}
This introduces a new field called collapsingOthers
that controls if I'm collapsing all nodes and programmatically expanding current. I take advantage that JavaScript allows me to expand current object dynamically adding properties.
See it here: http://jsfiddle.net/OnaBai/mVNw6/1/