Events

There are three basic kinds of events that GoJS deals with: DiagramEvents, InputEvents, and ChangedEvents.

Diagram Events

DiagramEvents represent general user-initiated changes to a diagram. You can register diagram event handlers by calling Diagram.addDiagramListener. Each kind of diagram event is distinguished by its name.

Currently defined diagram event names include:

For more details, please read the documentation for DiagramEvent.

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

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 updated. 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, that notices the changes to the model and decides what to record in the database. See the discussion of ChangedEvents, below, and the Update Demo.

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

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

  diagram.addDiagramListener("SelectionDeleting",
      function(e) {
        if (e.diagram.selection.count > 1) {
          e.cancel = true;
          showMessage("Cannot delete multiple selected 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 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.

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 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)

Changed Events

The third category of events in GoJS are notifications of state changes, mostly object property changes. The ChangedEvent records the kind of change that occurred and enough information to be able to undo and redo them.

Changed events are produced by both Model and Diagram. They are multicast events, so you can call Model.addChangedListener and Diagram.addChangedListener, as well as the corresponding removeChangedListener methods.

A Diagram always registers itself as a listener on its Model, so that it can automatically notice changes to the model and update its Parts accordingly. Furthermore the UndoManager, if enabled, automatically listens to changes to both the model and the diagram, so that it can record the change history and perform undo and redo.

In addition to the standard 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 correspond to any particular input or diagram event, these event handlers have custom arguments that are specific to the situation.

The most common such 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 property changes

For property changes, that information includes the ChangedEvent.object that was modified, the ChangedEvent.propertyName, and the ChangedEvent.oldValue and ChangedEvent.newValue values for that property. Property changes are identified by the ChangedEvent.change == ChangedEvent.Property.

Some changes represent structural changes to the model, not just simple model data changes. In such cases the ChangedEvent.modelChange property will be a non-empty string naming the kind of change. The following names for Property ChangedEvents correspond to structural model data changes:

The value of ChangedEvent.modelChange will be one of these strings. The value of ChangedEvent.propertyName depends on the name of the actual data property that was modified. For example, for the model property change "linkFromKey", the actual property name defaults to "from". But you might be using a different property name by having set GraphLinksModel.linkFromKeyProperty to some other data property name.

Any property can be changed on a node data or link data object, by calling Model.setDataProperty. Such a call will result in the property name to be recorded as the ChangedEvent.propertyName. These cases are treated as normal property changes, not structural model changes, so ChangedEvent.modelChange will be the empty string. The value of ChangedEvent.object will of course be the JavaScript object that was modified.

Finally, there are property changes on the model itself. For a listing of such properties, see the documentation for Model, GraphLinksModel, and TreeModel. These cases are treated as normal property changes, so ChangedEvent.modelChange will be the empty string. Both ChangedEvent.model and ChangedEvent.object will be the model itself.

Model collection changes

Other changed event kinds include ChangedEvent.Insert and ChangedEvent.Remove. In addition to all of the previously mentioned ChangedEvent properties used to record a property change, the ChangedEvent.oldParam and ChangedEvent.newParam provide the "index" information needed to be able to properly undo and redo the change.

The following property names for Insert and Remove ChangedEvents correspond to model changes to collections:

Transactions

The final kind of model changed event is ChangedEvent.Transaction. These are not strictly object changes in the normal sense, but they do notify when a transaction starts or finishes, or when an undo or redo starts or finishes.

The following values of ChangedEvent.propertyName describe the kind of transaction-related event that just occurred:

In each case the ChangedEvent.object is the Transaction holding a sequence of ChangedEvents. The ChangedEvent.oldValue is the name of the transaction -- the string passed to UndoManager.startTransaction or UndoManager.commitTransaction. The various standard commands and tools that perform transactions document the transaction name(s) that they employ. But your code can employ as many transaction names as you like.

It is commonplace to want to update a server database when a transaction has finished. Use the ChangedEvent.isTransactionFinished read-only property to detect that case. You'll want to implement a Changed listener as follows:

  // notice whenever a transaction or undo/redo has occurred
  diagram.model.addChangedListener(function(e) {
    if (e.isTransactionFinished) saveModel();
  });

Look at the Update Demo for a demonstration of how you can keep track of changes to a model when a transaction is committed or when an undo or redo is finished. The common pattern is to iterate over the ChangedEvents of the current Transaction in order to decide what to record in a database.

Clicking and Selecting

This example demonstrates both the "click" and the "selectionChanged" events:

  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.