Extending GoJS

GoJS can be extended in a variety of ways. The most common way to change the standard behavior is to set properties on the GraphObject, Diagram, CommandHandler, Tool, or Layout. But when no such properties exist, you might need to override methods of CommandHandler, Tool, Layout, Link, or Node. Methods that you can override are documented in the API reference. This page describes how to override methods, either by replacing a method on an instance (a feature of JavaScript) or by defining a subclass. You should not modify the prototypes of any of the GoJS classes.

Do not modify the prototypes of the GoJS classes.
Only use the properties and methods documented in the API.

In addition to our samples, GoJS provides an extensions gallery, showcasing the creation of custom tools and layouts. All of those classes and samples have been translated into TypeScript, available at ../extensionsTS/.

Command Handler

Overriding the CommandHandler allows you to alter default functionality and create your own key bindings. See the intro page on Commands for more. However, the techniques shown below for overriding methods on Tools and Layouts also applies to the CommandHandler.

Tools and Layouts

GoJS operates on nodes and links using many tools and layouts, all of which are subclasses of the Tool and Layout classes. See the intro page on Tools for more about Tools, and the intro page on Layouts for more about Layouts.

Tools can be modified, or they can be replaced in or added to the Diagram.toolManager. All tools must inherit from the Tool class or from a class that inherits from Tool.

Some of our samples, such as the Pipes sample, contain examples of custom tools. More custom tool examples are available in the extensions gallery. TypeScript versions of those classes and samples are available in ../extensionsTS/.

Layouts can be modified, or they can be used by setting Diagram.layout or Group.layout. All Layouts must inherit from the Layout class or a class that inherits from Layout.

Some of our samples, such as the Parse Tree sample, contain examples of custom layouts. More custom layout examples are available in the extensions gallery. TypeScript versions of those classes are available in ../extensionsTS/.

Overriding a Method Without Defining a Subclass

Often we can avoid subclassing a Tool in its entirety and merely override a single method. This is common when we want to make a small change to the behavior of a method. Here we show how to override the ClickSelectingTool.standardMouseSelect method by modifying the tool instance of a particular Diagram.

One can override Layout methods in this manner also, but that is rarely done -- layouts are almost always subclassed. It cannot be done for layouts that are the value of Group.layout because those layouts may be copied and cannot be shared.

Since we are not creating a new (sub)class, we set the method directly on the Diagram's ClickSelectingTool, which is referenced through its ToolManager. Typical scaffolding for overriding a method in such a manner is as follows:

  var tool = diagram.toolManager.clickSelectingTool;
  tool.standardMouseSelect = function() {
    // Maybe do something else before
    // ...

    // Be careful about using 'this' within such functions!

    // In cases where you want normal behavior, call the base functionality.
    // Note the reference to the prototype
    // and the call to 'call' passing it what 'this' should be.
    go.ClickSelectingTool.prototype.standardMouseSelect.call(tool);

    // Maybe do something else after
    // ...
  }

As a concrete example, we will override Tool.standardMouseSelect to select only Nodes and Links that have a width and height of less than 50 diagram units. This means that we must find the to-be-selected object using diagram.findPartAt, check its bounds, and quit if the bounds are too large. Otherwise, we call the base functionality to select as we normally might.

  diagram.nodeTemplate =
    $(go.Node, "Auto",
      $(go.Shape, "Rectangle",
        { fill: "white" },
        new go.Binding("fill", "color")),
      $(go.TextBlock,
        { margin: 5 },
        new go.Binding("text", "key"))
    );

  var tool = diagram.toolManager.clickSelectingTool;
  tool.standardMouseSelect = function() {
    var diagram = tool.diagram;
    var e = diagram.lastInput;
    // to select containing Group if Part.canSelect() is false
    var curobj = diagram.findPartAt(e.documentPoint, false);
    if (curobj !== null) {
      var bounds = curobj.actualBounds;
      // End the selection process if the bounds are greater than 50 width or height
      if (bounds.width > 50 || bounds.height > 50) {
        // If this was a left click with no modifier, we want to act the same as if
        // we are clicking on the Diagram background, so we clear the selection
        if (e.left && !e.control && !e.shift) {
          diagram.clearSelection();
        }
        // Then return, so that we do not call the base functionality
        return;
      }
    }
    // otherwise, call the base functionality
    go.ClickSelectingTool.prototype.standardMouseSelect.call(tool);
  }

  diagram.model = new go.Model([
    { key: "Alpha", color: "lightblue" },
    { key: "Epsilon", color: "thistle" },
    { key: "Psi", color: "lightcoral" },
    { key: "Gamma", color: "lightgreen" }
  ]);

Running this code, we see that the "Epsilon" and "Gamma" nodes are not selectable, because they are both wider than 50. Note that this custom tool does not change the behavior of other tools that might select, such as the DraggingTool or the DragSelectingTool.

Overriding Methods by Subclassing a Layout

Layouts can be subclassed to create custom Layouts that inherit the properties and methods of an existing layout. Subclassing in GoJS requires a few key steps:

To create a new Layout, called CascadeLayout, we would start with the following scaffolding:

  function CascadeLayout() {
    // Note the direct constructor call, no use of "prototype"
    go.Layout.call(this);
    // new properties go here, on "this"
  }
  go.Diagram.inherit(CascadeLayout, go.Layout);

  // Note setting the method on the prototype
  CascadeLayout.prototype.doLayout = function(coll) {
    // Layout logic goes here.
    // You can reliably use "this" to refer to the layout instance
    // on which this method was called.
  }

Layouts commonly need additional properties that act as layout options. To add a "offset" property to CascadeLayout, we will use the convention that an underscore member is private, and will set a default value in the constructor:

  function CascadeLayout() {
    go.Layout.call(this);
    this._offset = new go.Size(12, 12);
  }

Then, we use Object.defineProperty to make a "public" getter and setter. Getters and setters allow us to do type checking and have side effects. This setter makes sure the offset value is a go.Size object and invalidates the layout only if the value has changed.

  Object.defineProperty(CascadeLayout.prototype, "offset", {
    get: function() { return this._offset; },
    set: function(val) {
      if (!(val instanceof go.Size)) {
        throw new Error("new value for CascadeLayout.offset must be a Size, not: " + val);
      }
      if (!this._offset.equals(val)) {
        this._offset = val;
        this.invalidateLayout();
      }
    }
  });

Lastly we'll define a Layout.doLayout, being sure to look at the documentation and accomodate all possible input, as doLayout has one argument that can either be a Diagram, or a Group, or an Iterable collection.

All together, we can see the cascade layout in action:

  /**
  * @constructor
  * @extends Layout
  * @class
  * This layout arranges nodes in a cascade specified by the offset property
  */
  function CascadeLayout() {
    go.Layout.call(this);
    this._offset = new go.Size(12, 12);
  }
  go.Diagram.inherit(CascadeLayout, go.Layout);

  Object.defineProperty(CascadeLayout.prototype, "offset", {
    get: function() { return this._offset; },
    set: function(val) {
      if (!(val instanceof go.Size)) {
        throw new Error("new value for CascadeLayout.offset must be a Size, not: " + val);
      }
      if (!this._offset.equals(val)) {
        this._offset = val;
        this.invalidateLayout();
      }
    }
  });

  /**
  * This method positions all Nodes and ignores all Links.
  * @this {CascadeLayout}
  * @param {Diagram|Group|Iterable} coll the collection of Parts to layout.
  */
  CascadeLayout.prototype.doLayout = function(coll) {
    // get the Nodes and Links to be laid out
    var parts = this.collectParts(coll);

    // Start the layout at the arrangement origin, a property inherited from Layout
    var x = this.arrangementOrigin.x;
    var y = this.arrangementOrigin.y;
    var offset = this.offset;

    var it = parts.iterator;
    while (it.next()) {
      var node = it.value;
      if (!(node instanceof go.Node)) continue;  // ignore Links
      node.move(new go.Point(x, y));
      x += offset.width;
      y += offset.height;
    }
  }
  // end of CascadeLayout

  // Regular diagram setup:

  diagram.layout = new CascadeLayout();

  diagram.nodeTemplate =
    $(go.Node, "Auto",
      $(go.Shape, "Rectangle",
        { fill: "white" },
        new go.Binding("fill", "color")),
      $(go.TextBlock,
        { margin: 5 },
        new go.Binding("text", "key"))
    );

  diagram.model = new go.Model([
    { key: "Alpha", color: "lightblue" },
    { key: "Beta", color: "thistle" },
    { key: "Delta", color: "lightcoral" },
    { key: "Gamma", color: "lightgreen" }
  ]);