您可以使用 diagram.selection 获取要删除的项目:
var nodeToDelete = mydiagram.selection.iterator.first();
接下来要查找此节点的所有子节点,我推荐一个递归函数,它将执行以下操作:
- 取要删除的节点,
- 使用 mydiagram.getChildrenNodes(nodeToDelete) 查找所有连接的节点
- 遍历 cconnected 节点
- 检查每个节点是否是子节点,使用 linkNodeModel 并检查链接是否从当前节点到子节点。
- 然后用这个子节点再次调用递归函数
- 递归函数将返回一个包含所有子节点的数组
然后你可以删除它们。
您的代码将如下所示:
function deleteNode()
{
// TAKE NOTE - This will get all selections so you need to handel this
// If you have multiple select enabled
var nodeToDelete = mydiagram.selection.iterator.first();
var childNodes = getChildNodes(deletedItem);
//Remove linked children
$.each(childNodes, function()
{
myDiagram.remove(this);
});
// Then also delete the actual node after the children was deleted
// TAKE NOTE - This will delete all selections so you need to handle this
// If you have multiple select enabled
mydiagram.commandHandler.deleteSelection();
}
递归函数不断检查每个节点的子节点并将它们添加到数组中:
function getChildNodes(deleteNode)
{
var children = [];
var allConnected= deleteNode.findNodesConnected();
while (allConnected.next())
{
var child = allConnected.value;
// Check to see if this node is a child:
if (isChildNode(deleteNode, child))
{
// add the current child
children.push(child);
// Now call the recursive function again with the current child
// to get its sub children
var subChildren = getChildrenNodes(child);
// add all the children to the children array
$.each(subChildren, function()
{
children.push(this);
});
}
}
// return the children array
return children;
}
此函数将通过查看图中的链接并检查当前节点和子节点的往返来检查节点是否为子节点:
function isChildNode(currNode, currChild)
{
var links = myDiagram.links.iterator;
while (links.next())
{
// Here simply look at the link to determine the direction by checking the direction against the currNode and the child node. If from is the current node and to the child node
// then you know its a vhild
var currentLinkModel = links.value.data;
if (currentLinkModel.from === currNode.data.key && currentLinkModel.to === currChild.data.key)
{
return true;
}
}
return false;
}