簡體   English   中英

GoJS在不知道父節點密鑰的情況下刪除子節點

[英]GoJS delete child nodes without knowing parent node's key

我有一個帶有自定義模型的goJS圖。 當將一個節點放到另一個節點上時,我會在mouseDrop觸發時鏈接它們,並在diagram.model的鏈接數據中設置from和to:

mydiagram.model.addLinkData({ from: oldNodeModel.key, to: dragNodeModel.key });

這一切都很好。 在我的節點模板中,我有一個自定義模板,該模板在節點周圍放置一個帶有刪除按鈕的面板。 該刪除按鈕只是帶有點擊事件的圖像。

現在,當我單擊“刪除圖像/按鈕”時,我要立即刪除此圖像及其所有子節點。

我的問題是我找不到孩子。

我有諸如findNodesOutOf類的用戶事件,該事件findNodesOutOf產生任何結果,而findNodesConnected會查找父節點和子節點並刪除很多-這不是我想要的。

知道我該如何解決嗎?

您可以使用圖表來刪除要刪除的項目:

var nodeToDelete = mydiagram.selection.iterator.first();

接下來,找到該節點的所有子節點,我建議使用一個遞歸函數,該函數將執行以下操作:

  1. 輸入您要刪除的節點,
  2. 使用mydiagram.getChildrenNodes(nodeToDelete)查找與其連接的所有節點
  3. 遍歷連接的節點
  4. 通過使用linkNodeModel來檢查每個節點是否是子節點,並檢查鏈接是否從當前節點到子節點。
  5. 然后使用此子節點再次調用遞歸函數
  6. 遞歸函數將返回一個包含所有子節點的數組

然后,您可以刪除它們。

您的代碼將如下所示:

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();
}

遞歸函數不斷檢查每個節點的子節點,並將其添加到aray中:

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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM