事件

There are three basic kinds of events that GoJS deals with: DiagramEvents, InputEvents, and ChangedEvents. This page discusses the first two; see Changed Events for the last kind of event.

图表的事件

DiagramEvents represent general user-initiated changes to a diagram. You can register one or more diagram event handlers by calling Diagram.addDiagramListener. You can also register a diagram event handler in Diagram initialization when calling GraphObject,make. Each kind of diagram event is distinguished by its name.

Currently defined diagram event names include:

  • "InitialAnimationStarting", the initial default animation is about to start; do not modify the diagram or its model in the event listener. This can be useful for modifying the AnimationManager.defaultAnimation to make a custom initial animation. See AnimationManager.initialAnimationStyle for details.
  • "AnimationStarting", a default animation (AnimationManager.defaultAnimation); do not modify the diagram or its model in the event listener.
  • "AnimationFinished", a default animation (AnimationManager.defaultAnimation) ; do not modify the diagram or its model in the event listener.
  • "BackgroundSingleClicked" 背景单击事件, when a mouse left-button single-click happened in the background of the Diagram, not on a Part; if you make any changes, start and commit your own transaction.
  • "BackgroundDoubleClicked" 背景双击事件, when a mouse left-button double-click happened in the background of the Diagram, not on a Part; if you make any changes, start and commit your own transaction.
  • "BackgroundContextClicked"背景右键事件, when a mouse right-button single-click happened in the background of the Diagram, not on a Part; if you make any changes, start and commit your own transaction.
  • "ChangingSelection", an operation is about to change the Diagram.selection collection, which is also the value of the DiagramEvent.subject; do not make any changes to the selection or the diagram or the model in the event listener; note that just setting Part.isSelected will not raise this event, but tools and commands will.
  • "ChangedSelection", an operation has just changed the Diagram.selection collection, which is also the value of the DiagramEvent.subject; do not make any changes to the selection or the diagram or the model in the event listener; note that just setting Part.isSelected will not raise this event, but tools and commands will.
  • "ClipboardChanged", Parts have been copied to the clipboard by CommandHandler.copySelection; the DiagramEvent.subject is the collection of Parts; if you make any changes, start and commit your own transaction.
  • "ClipboardPasted", Parts have been copied from the clipboard into the Diagram by CommandHandler.pasteSelection; the DiagramEvent.subject is the Diagram.selection, and this is called within a transaction, so that you do not have to start and commit your own transaction.
  • "DocumentBoundsChanged", the area of the diagram's Parts, Diagram.documentBounds, has changed; the DiagramEvent.parameter is the old Rect.
  • "ExternalObjectsDropped" (节点或线等)部件拖放生成事件, Parts have been copied into the Diagram by drag-and-drop from outside of the Diagram; the DiagramEvent.subject is the set of Parts that were dropped (which is also the Diagram.selection), the DiagramEvent.parameter is the source Diagram, and this is called within a transaction, so that you do not have to start and commit your own transaction.
  • "GainedFocus", the diagram has gained keyboard focus, such as after a call to Diagram.focus.
  • "InitialLayoutCompleted", the whole diagram layout has updated for the first time since a major change to the Diagram, such as replacing the Model; if you make any changes, you do not need to perform a transaction.
  • "LayoutCompleted", the whole diagram layout has just been updated; if you make any changes, you do not need to perform a transaction.
  • "LinkDrawn" 线创建事件,用户刚刚使用LinkingTool创建了一个新链接;DiagramEvent.subject 是新的链接;该事件已在事务中调用,不用启动和提交事务.
  • "LinkRelinked",线重新链接事件 the user has just reconnected an existing Link using RelinkingTool or DraggingTool; the DiagramEvent.subject is the modified Link, the DiagramEvent.parameter is the GraphObject port that the link was disconnected from, and this is called within a transaction, so that you do not have to start and commit your own transaction..
  • "LinkReshaped", the user has just rerouted an existing Link using LinkReshapingTool; the DiagramEvent.subject is the modified Link, the DiagramEvent.parameter is the List of Points of the link's original route, and this is called within a transaction, so that you do not have to start and commit your own transaction..
  • "LostFocus", the diagram has lost keyboard focus ("blur").
  • "Modified", the Diagram.isModified property has been set to a new value -- useful for marking a window as having been modified since the last save; do not modify the Diagram or its Model in the event listener.
  • "ObjectSingleClicked" 单击事件, 监听在图形对象GraphObject上的单击; 返回的 DiagramEvent.subject 是一个图形对象 GraphObject; 如果您做了任何更改,请启动并提交您自己的事务。
  • "ObjectDoubleClicked" 双击事件, 监听在图形对象GraphObject上的双击; 返回的 DiagramEvent.subject 是一个图形对象 GraphObject; 如果您做了任何更改,请启动并提交您自己的事务。
  • "ObjectContextClicked" 右键事件, 监听在图形对象GraphObject上的右键单击; 返回的DiagramEvent.subject 是一个图形对象 GraphObject; 如果您做了任何更改,请启动并提交您自己的事务。
  • "PartCreated", 用户通过ClickCreatingTool创建一个新的Part; DiagramEvent.subject 是新创建的Part, 该事件已在事务中调用,不必启动和提交事务.
  • "PartResized" Part大小改变事件, 用户通过ResizingTool改变了一个GraphObject的大小; the DiagramEvent.subject is the GraphObject, the DiagramEvent.parameter is the original Size, 该事件已在事务中调用,不必启动和提交事务.
  • "PartRotated" Part旋转事件, 用户通过RotatingTool改变了一个GraphObject的角度; the DiagramEvent.subject is the GraphObject, the DiagramEvent.parameter is the original angle in degrees, 该事件已在事务中调用,不必启动和提交事务.
  • "SelectionMoved" 拖动事件, the user has moved selected Parts by DraggingTool; the DiagramEvent.subject 是移动的Parts, 该事件已在事务中调用,不必启动和提交事务.
  • "SelectionCopied" 复制事件, the user has copied selected Parts by DraggingTool; the DiagramEvent.subject 是复制出来的Parts, 该事件已在事务中调用,不必启动和提交事务.
  • "SelectionDeleting" 删除前事件,用户即将通过 CommandHandler.deleteSelection删除所选部件; DiagramEvent.subject 是选择Diagram.selection要删除的部分集合,该事件已在事务中调用,不必启动和提交事务.
  • "SelectionDeleted" 删除后事件,用户即已通过 CommandHandler.deleteSelection删除所选部件; DiagramEvent.subject 是已删除部分的集合,该事件已在事务中调用,不必启动和提交事务.
  • "SelectionGrouped" 新建组事件, the user has made a new Group out of the selected Parts by CommandHandler.groupSelection; the DiagramEvent.subject is the new Group,
    该事件已在事务中调用,不必启动和提交事务.
  • "SelectionUngrouped" 删除组事件, the user has removed a selected Group but kept its members by CommandHandler.ungroupSelection; the DiagramEvent.subject is the collection of Groups that were ungrouped, the DiagramEvent.parameter is the collection of former member Parts that were ungrouped, 该事件已在事务中调用,不必启动和提交事务.
  • "SubGraphCollapsed" 子图折叠事件, the user has collapsed selected Groups by CommandHandler.collapseSubGraph; the DiagramEvent.subject is the collection of Groups that were collapsed, 该事件已在事务中调用,不必启动和提交事务.
  • "SubGraphExpanded" 子图展开事件, the user has expanded selected Groups by CommandHandler.expandSubGraph; the DiagramEvent.subject is the collection of Groups that were expanded, 该事件已在事务中调用,不必启动和提交事务.
  • "TextEdited"文本快修改事件, the user has changed the string value of a TextBlock by TextEditingTool; the DiagramEvent.subject 是编辑后的文本块, the DiagramEvent.parameter is the original string, 该事件已在事务中调用,不必启动和提交事务.
  • "TreeCollapsed" 树折叠事件, the user has collapsed selected Nodes with subtrees by CommandHandler.collapseTree; the DiagramEvent.subject 是被折叠节点的集合, 该事件已在事务中调用,不必启动和提交事务.
  • "TreeExpanded" 树展开事件, the user has expanded selected Nodes with subtrees by CommandHandler.expandTree; the DiagramEvent.subject是展开后的节点集合, 该事件已在事务中调用,不必启动和提交事务.
  • "ViewportBoundsChanged", the visible area of the Diagram, Diagram.viewportBounds, has changed; the DiagramEvent.subject is an object whose "scale" property is the old Diagram.scale value, whose "position" property is the old Diagram.position value, and whose "bounds" property is the old Diagram.viewportBounds value; the DiagramEvent.parameter is also the old viewportBounds Rect. Do not modify the Diagram position or scale (i.e. the viewport bounds) in the listener.

    DiagramEvents do not necessarily correspond to mouse events or keyboard events or touch events. Nor do they necessarily correspond to changes to the diagram's model -- for tracking such changes, use Model.addChangedListener or Diagram.addModelChangedListener. DiagramEvents only occur because the user did something, perhaps indirectly.

    In addition to the DiagramEvent listeners there are also circumstances where detecting such changes is common enough to warrant having properties that are event handlers. Because these events do not necessarily correspond to any particular input or diagram event, these event handlers have custom arguments that are specific to the situation.

    One very common such event property is GraphObject.click, which if non-null is a function that is called whenever the user clicks on that object. This is most commonly used to specify behavior for "Button"s, but it and the other "click" event properties, "doubleClick" and "contextClick", can be useful on any GraphObject.

    Another common event property is Part.selectionChanged, which (if non-null) is called whenever Part.isSelected changes. In this case the event hander function is passed a single argument, the Part. There is no need for additional arguments because the function can check the current value of Part.isSelected to decide what to do.

    Model ChangedEvents are more complete and reliable than depending on DiagramEvents. For example, the "LinkDrawn" DiagramEvent is not raised when code adds a link to a diagram. That DiagramEvent is only raised when the user draws a new link using the LinkingTool. Furthermore the link has not yet been routed, so Link.points will not have been computed. In fact, creating a new link may invalidate a Layout, so all of the nodes may be moved in the near future.

    Sometimes you want to update a database as the user makes changes to a diagram. Usually you will want to implement a Model ChangedEvent listener, by calling Model.addChangedListener or Diagram.addModelChangedListener, that notices the changes to the model and decides what to record in the database. See the discussion of Changed Events and the Update Demo.

    This example demonstrates handling several diagram events: "ObjectSingleClicked", "BackgroundDoubleClicked", and "ClipboardPasted".

      function showMessage(s) {
        document.getElementById("diagramEventsMsg").textContent = s;
      }
    
      diagram.addDiagramListener("ObjectSingleClicked",
          function(e) {
            var part = e.subject.part;
            if (!(part instanceof go.Link)) showMessage("Clicked on " + part.data.key);
          });
    
      diagram.addDiagramListener("BackgroundDoubleClicked",
          function(e) { showMessage("Double-clicked at " + e.diagram.lastInput.documentPoint); });
    
      diagram.addDiagramListener("ClipboardPasted",
          function(e) { showMessage("Pasted " + e.diagram.selection.count + " parts"); });
    
      var nodeDataArray = [
        { key: "Alpha" },
        { key: "Beta", group: "Omega" },
        { key: "Gamma", group: "Omega" },
        { key: "Omega", isGroup: true },
        { key: "Delta" }
      ];
      var linkDataArray = [
        { from: "Alpha", to: "Beta" },  // from outside the Group to inside it
        { from: "Beta", to: "Gamma" },  // this link is a member of the Group
        { from: "Omega", to: "Delta" }  // from the Group to a Node
      ];
      diagram.model = new go.GraphLinksModel(nodeDataArray, linkDataArray);
    

    (message)

    Input Events

    When a low-level HTML DOM event occurs, GoJS canonicalizes the keyboard/mouse/touch event information into a new InputEvent that can be passed to various event-handling methods and saved for later examination.

    An InputEvent keeps the InputEvent.key for keyboard events, the InputEvent.button for mouse events, the InputEvent.viewPoint for mouse and touch events, and InputEvent.modifiers for keyboard and mouse events.

    The diagram's event handlers also record the InputEvent.documentPoint, which is the InputEvent.viewPoint in document coordinates at the time of the mouse event, and the InputEvent.timestamp, which records the time that the event occurred in milliseconds.

    The InputEvent class also provides many handy properties for particular kinds of events. Examples include InputEvent.control (if the control key had been pressed) and InputEvent.left (if the left/primary mouse button was pressed).

    Some tools find the "current" GraphObject at the mouse point. This is remembered as the InputEvent.targetObject.

    Higher-level input events

    Some tools detect a sequence of input events to compose somewhat more abstract user events. Examples include "click" (mouse-down-and-up very close to each other) and "hover" (motionless mouse for some time). The tools will call an event handler (if there is any) for the current GraphObject at the mouse point. The event handler is held as the value of a property on the object. It then also "bubbles" the event up the chain of GraphObject.panels until it ends with a Part. This allows a "click" event handler to be declared on a Panel and have it apply even if the click actually happens on an element deep inside the panel. If there is no object at the mouse point, the event occurs on the diagram.

    Click-like event properties include GraphObject.click, GraphObject.doubleClick, and GraphObject.contextClick. They also occur when there is no GraphObject -- the event happened in the diagram's background: Diagram.click, Diagram.doubleClick, and Diagram.contextClick. These are all properties that you can set to a function that is the event handler. These events are caused by both mouse events and touch events.

    Mouse-over-like event properties include GraphObject.mouseEnter, GraphObject.mouseOver, and GraphObject.mouseLeave. But only Diagram.mouseOver applies to the diagram.

    Hover-like event properties include GraphObject.mouseHover and GraphObject.mouseHold. The equivalent diagram properties are Diagram.mouseHover and Diagram.mouseHold.

    There are also event properties for dragging operations: GraphObject.mouseDragEnter, GraphObject.mouseDragLeave, and GraphObject.mouseDrop. These apply to stationary objects, not the objects being dragged. And they also occur when dragging by touch events, not just mouse events.

    This example demonstrates handling three higher-level input events: clicking on nodes and entering/leaving groups.

      function showMessage(s) {
        document.getElementById("inputEventsMsg").textContent = s;
      }
    
      diagram.nodeTemplate =
        $(go.Node, "Auto",
          $(go.Shape, "Ellipse", { fill: "white" }),
          $(go.TextBlock,
            new go.Binding("text", "key")),
          { click: function(e, obj) { showMessage("Clicked on " + obj.part.data.key); } }
        );
    
      diagram.groupTemplate =
        $(go.Group, "Vertical",
          $(go.TextBlock,
            { alignment: go.Spot.Left, font: "Bold 12pt Sans-Serif" },
            new go.Binding("text", "key")),
          $(go.Panel, "Auto",
            $(go.Shape, "RoundedRectangle",
              { name: "SHAPE",
                parameter1: 14,
                fill: "rgba(128,128,128,0.33)" }),
            $(go.Placeholder, { padding: 5 })
          ),
          { mouseEnter: function(e, obj, prev) {  // change group's background brush
                var shape = obj.part.findObject("SHAPE");
                if (shape) shape.fill = "red";
              },
            mouseLeave: function(e, obj, next) {  // restore to original brush
                var shape = obj.part.findObject("SHAPE");
                if (shape) shape.fill = "rgba(128,128,128,0.33)";
              } });
    
      var nodeDataArray = [
        { key: "Alpha" },
        { key: "Beta", group: "Omega" },
        { key: "Gamma", group: "Omega" },
        { key: "Omega", isGroup: true },
        { key: "Delta" }
      ];
      var linkDataArray = [
        { from: "Alpha", to: "Beta" },  // from outside the Group to inside it
        { from: "Beta", to: "Gamma" },  // this link is a member of the Group
        { from: "Omega", to: "Delta" }  // from the Group to a Node
      ];
      diagram.model = new go.GraphLinksModel(nodeDataArray, linkDataArray);
    

    (message)

    单击 和 选择

    这个例子演示了单击"click" 和选择改变 "selectionChanged" 事件:

      function showMessage(s) {
        document.getElementById("changeMethodsMsg").textContent = s;
      }
    
      diagram.nodeTemplate =
        $(go.Node, "Auto",
          { selectionAdorned: false },
          $(go.Shape, "Ellipse", { fill: "white" }),
          $(go.TextBlock,
            new go.Binding("text", "key")),
          {
            click: function(e, obj) { showMessage("Clicked on " + obj.part.data.key); },
            selectionChanged: function(part) {
                var shape = part.elt(0);
                shape.fill = part.isSelected ? "red" : "white";
              }
          }
        );
    
      var nodeDataArray = [
        { key: "Alpha" }, { key: "Beta" }, { key: "Gamma" }
      ];
      var linkDataArray = [
        { from: "Alpha", to: "Beta" },
        { from: "Beta", to: "Gamma" }
      ];
      diagram.model = new go.GraphLinksModel(nodeDataArray, linkDataArray);
    

    (message)

    Try Ctrl-A to select everything. Note the distinction between the GraphObject.click event property and the Part.selectionChanged event property. Both are methods that get called when something has happened to the node. The GraphObject.click occurs when the user clicks on the node, which happens to select the node. But the Part.selectionChanged occurs even when there is no click event or even any mouse event -- it was due to a property change to the node.

  • 加入 GoJS 交流群
    GoJS 交流群 (769862113)