Contextual Node Menus

The AdvancedTree component allows you to set contextual right click menus for nodes. These can change for each node, allowing you to set a custom menu for each individual node. The way this is accomplished it not through the direct assignment of menus to nodes, but through a custom function, specified in the AdvancedTree's nodeMenuFunction property that can be called when a menu needs to be rendered that returns the proper menu for the node clicked.

  1. Write a function that takes as an argument a TreeNode instance and returns an array of ContextMenuItems for that node.
  2. import com.flashloaded.ui.tree.nodes.TreeNode;
    import flash.events.ContextMenuEvent;
    import flash.ui.ContextMenuItem;

    function makeMenu(node:TreeNode):Array {
      var items:Array = [];
      var item:ContextMenuItem;
      if (node.open) {
        item = new ContextMenuItem("close node");
        item.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, onCloseNode);
        items.push(item);
      } else if (node.numChildren > 0) {
        item = new ContextMenuItem("open node");
        item.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, onOpenNode);
        items.push(item);
      }
      if (node != tree.rootNode) {
        item = new ContextMenuItem("delete node");
        item.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, onDeleteNode);
        items.push(item);
      }
      return items;
    }

    This is an example of a function that accepts a TreeNode instance and, based on the node, creates an array of menu items to display.

  3. Assign the custom function to the AdvancedTree instance's nodeMenuFunction property.
  4. tree.nodeMenuFunction = makeMenu;

    Now whenever a node is right clicked, the custom function will be called and the menu that appears will be controlled by what is returned from the function.