问题
I have a Tree element with MultiSelect mode, which looks good with checkboxes in every tree item. I wanted to make it so if I select one item, all of its children get selected as well. I have the tree in the view:
<Tree selectionChange="onPress" itemPress="onPress" includeItemInSelection="true" mode="MultiSelect" items="{path: '/'}" id="Tree">
<headerToolbar>
<Toolbar>
<content>
<Title level="H2" text="Title"/>
<ToolbarSpacer/>
</content>
</Toolbar>
</headerToolbar>
<StandardTreeItem title="{text}"/>
</Tree>
I wanted to know if SAPUI5 had a property for its trees like "Check Children" or something similar. And if not, how could I do it.
Thanks.
回答1:
There are two approaches that come to mind:
- Using binding (the 'better' way).
- Using JS manipulation (the 'harder' way - because the TreeItem has no method for retrieving the child items).
I will show you the 'better' way for doing things. The 'harder' one you can do as an extension of this method (if you really want to go that way, I can also add info about how to do it).
Basically you need to extend your model by adding a selected
flag. Assuming that you have a typical model structure (as in the explored example), you can use this function:
function addSelectedFlag(aNodes, bSelected) {
jQuery.each(aNodes, function(iIndex, oNode) {
oNode.selected = bSelected;
if (oNode.nodes) {
addSelectedFlag(oNode.nodes, bSelected);
}
});
}
Then, when the selection changes, you can do something along the lines of:
onSelect: function(oEvent) {
var aItems = oEvent.getParameter("listItems") || [],
oModel = this.getView().getModel();
jQuery.each(aItems, function(iIndex, oItem) {
var oNode = oItem.getBindingContext().getObject(),
bSelected = oItem.getSelected();
if (oNode.nodes) {
addSelectedFlag(oNode.nodes, bSelected);
}
});
oModel.refresh();
}
When you specify the template fro your item, you must also bind the selection:
<StandardTreeItem title="{text}" selected="{selected}"/>
I made a working JsFiddle out of this: https://jsfiddle.net/n4frtzd8/1/
来源:https://stackoverflow.com/questions/43139542/tree-selection-sapui5-with-checkboxes-auto-check-child-nodes-when-parent-node