Data Binding

Data binding is a way to extract a value from a source object and set a property on a target object. The target objects are normally GraphObjects; the source objects are usually JavaScript data objects held in a model.

You could write code that gets a desired value from the model data, searches the Diagram for the appropriate Part, searches for the target GraphObject within the visual tree of that Part, and then sets one or more properties on that GraphObject with that value, perhaps after modifying or converting the original value in a way appropriate for the individual properties. However data binding offers a declarative way to specify such behavior just by supplying a Binding that names the properties on the source object and on the target object.

Trying to bind a non-existent property of a GraphObject will probably result in a warning or error that you can see in the console log. Always check the console log for any kinds of potential exceptions that are normally suppressed by the binding system.

The Relationships of Parts and Data and Binding

First, look at a diagram that includes comments about the GraphObjects used to build some example nodes and links:

The two Nodes and one Link belong to the Diagram and are on the left side, with shadows. The TreeModel and the two data objects in its Model.nodeDataArray are on the right side, in gray.

Each Node and Link has a Panel.data property that references the data object in the model. Thus it is easy, given a Node, to refer to all of the data properties that you have put on the data in the model. These references are drawn as gray links.

Each Node also has three Bindings, drawn with dashed green lines:

The use of templates and data binding greatly simplify the information that must be stored in model data, and allow great flexibility in representing nodes and links in various manners independent of the model data. But not all data properties need to be used in Bindings in the template.

Note that Bindings are not references from the data to any Part. The whole point of separating models from diagrams is to avoid references from data to Diagrams or Nodes or Links or Tools. The only references from diagram to model are the Diagram.model property and each node or link's Panel.data property.

Binding string and number properties

It is easy to data bind GraphObject properties to data properties. In this example we not only data bind TextBlock.text and Shape.fill in nodes to property values of node data, but for thicker colored lines we also bind Shape.stroke and Shape.strokeWidth in links to property values of link data.

All you need to do is add to the target GraphObject a new Binding that names the target property on the visual object and the source property on the data object. Of course the target property must be a settable property; some GraphObject properties are not settable. If you specify a target property name that does not exist you will get warning messages in the console. If the source property value is undefined, the binding is not evaluated.

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

  diagram.linkTemplate =
    $(go.Link,
      $(go.Shape,
        new go.Binding("stroke", "color"),  // shape.stroke = data.color
        new go.Binding("strokeWidth", "thick")),  // shape.strokeWidth = data.thick
      $(go.Shape,
        { toArrow: "OpenTriangle", fill: null },
        new go.Binding("stroke", "color"),  // shape.stroke = data.color
        new go.Binding("strokeWidth", "thick"))  // shape.strokeWidth = data.thick
    );

  var nodeDataArray = [
    { key: "Alpha", color: "lightblue" },
    { key: "Beta", color: "pink" }
  ];
  var linkDataArray = [
    { from: "Alpha", to: "Beta", color: "blue", thick: 2 }
  ];
  diagram.model = new go.GraphLinksModel(nodeDataArray, linkDataArray);

Note that there are two bindings using the "color" property of the source link data. There is one for each target Shape in the Link template; each binds the Shape.stroke property.

Binding object properties such as Part.location

You can also data bind properties that have values that are objects. For example it is common to data bind the Part.location property.

The value of Part.location is a Point, so in this example the data property must be a Point.

  diagram.nodeTemplate =
    $(go.Node, "Auto",
      new go.Binding("location", "loc"),  // get the Node.location from the data.loc value
      $(go.Shape, "RoundedRectangle",
        { fill: "white" },
        new go.Binding("fill", "color")),
      $(go.TextBlock,
        { margin: 5 },
        new go.Binding("text", "key"))
    );

  var nodeDataArray = [
    // for each node specify the location using Point values
    { key: "Alpha", color: "lightblue", loc: new go.Point(0, 0) },
    { key: "Beta", color: "pink", loc: new go.Point(100, 50) }
  ];
  var linkDataArray = [
    { from: "Alpha", to: "Beta" }
  ];
  diagram.model = new go.GraphLinksModel(nodeDataArray, linkDataArray);

For conciseness the rest of these examples make use of the default Diagram.linkTemplate.

Conversion functions

But what if you want the data property value for the location to be something other than a Point? You can provide a conversion function that converts the actual data property value to the needed value type or format.

For situations like this example, the Point class includes a static function, Point.parse, that you can use to convert a string into a Point object. It expects two numbers to be in the input string, representing the Point.x and Point.y values. It returns a Point object with those values.

You can pass a conversion function as the third argument to the Binding constructor. In this case it is Point.parse. This allows the location to be specified in the form of a string ("100 50") rather than as an expression that returns a Point. For data properties on model objects, you will often want to use strings as the representation of Points, Sizes, Rects, Margins, and Spots, rather than references to objects of those classes. Strings are easily read and written in JSON and XML. Trying to read/write classes of objects would take extra space and would require additional cooperation on the part of both the writer and the reader.

  diagram.nodeTemplate =
    $(go.Node, "Auto",
      new go.Binding("location", "loc", go.Point.parse),  // convert string into a Point value
      $(go.Shape, "RoundedRectangle",
        { fill: "white" },
        new go.Binding("fill", "color")),
      $(go.TextBlock,
        { margin: 5 },
        new go.Binding("text", "key"))
    );

  var nodeDataArray = [
    { key: "Alpha", color: "lightblue", loc: "0 0" },  // note string values for location
    { key: "Beta", color: "pink", loc: "100 50" }
  ];
  var linkDataArray = [
    { from: "Alpha", to: "Beta" }
  ];
  diagram.model = new go.GraphLinksModel(nodeDataArray, linkDataArray);

Conversion functions can be named or anonymous functions. They take a data property value and return a value suitable for the property that is being set. They should not have any side-effects. They may get called any number of times in any order.

Here is an example that has several Shape properties data-bound to the same boolean data property named "highlight". Each conversion function takes the boolean value and returns the appropriate value for the property that is data-bound. This makes it trivial to control the appearance of each node from the data by setting the "highlight" data property to be either false or true.

  diagram.nodeTemplate =
    $(go.Node, "Auto",
      new go.Binding("location", "loc", go.Point.parse),
      $(go.Shape, "RoundedRectangle",
        { // default values if the data.highlight is undefined:
          fill: "yellow", stroke: "orange", strokeWidth: 2 },
        new go.Binding("fill", "highlight", function(v) { return v ? "pink" : "lightblue"; }),
        new go.Binding("stroke", "highlight", function(v) { return v ? "red" : "blue"; }),
        new go.Binding("strokeWidth", "highlight", function(v) { return v ? 3 : 1; })),
      $(go.TextBlock,
        { margin: 5 },
        new go.Binding("text", "key"))
    );

  var nodeDataArray = [
    { key: "Alpha", loc: "0 0", highlight: false },
    { key: "Beta", loc: "100 50", highlight: true },
    { key: "Gamma", loc: "0 100" }  // highlight property undefined: use defaults
  ];
  var linkDataArray = [
    { from: "Alpha", to: "Beta" }
  ];
  diagram.model = new go.GraphLinksModel(nodeDataArray, linkDataArray);

Note that a conversion function can only return property values. You cannot return GraphObjects to replace objects in the visual tree of the Part. If you need to show different GraphObjects based on bound data, you can bind the GraphObject.visible or the GraphObject.opacity property. If you really want different visual structures you can use multiple templates (Template Maps).

Changing data values

The examples above all depend on the data bindings being evaluated when the Part has been created and its Panel.data property is set to refer to the corresponding node or link data. These actions occur automatically when the Diagram creates diagram parts for the data in the model upon setting Diagram.model.

However, GoJS cannot know when the data property of an arbitrary JavaScript object has been modified. If you want to change some data object in a model and have the diagram be automatically updated, what you should do depends on the nature of the property that you are changing.

For most data properties, ones that the model does not treat specially but are data-bound, you can just call Model.setDataProperty. In this example we modify the value of "highlight" on a node data object. For fun, this modification occurs about twice a second.

  diagram.nodeTemplate =
    $(go.Node, "Auto",
      { locationSpot: go.Spot.Center },
      $(go.Shape, "RoundedRectangle",
        { // default values if the data.highlight is undefined:
          fill: "yellow", stroke: "orange", strokeWidth: 2 },
        new go.Binding("fill", "highlight", function(v) { return v ? "pink" : "lightblue"; }),
        new go.Binding("stroke", "highlight", function(v) { return v ? "red" : "blue"; }),
        new go.Binding("strokeWidth", "highlight", function(v) { return v ? 3 : 1; })),
      $(go.TextBlock,
        { margin: 5 },
        new go.Binding("text", "key"))
    );

  diagram.model.nodeDataArray = [
    { key: "Alpha", highlight: false }  // just one node, and no links
  ];

  function flash() {
    var model = diagram.model;
    // all model changes should happen in a transaction
    model.startTransaction("flash");
    var data = model.nodeDataArray[0];  // get the first node data
    model.setDataProperty(data, "highlight", !data.highlight);
    model.commitTransaction("flash");
  }
  function loop() {
    setTimeout(function() { flash(); loop(); }, 500);
  }
  loop();

Changing graph structure

For data properties that the model knows about, such as "to" or "from" for link data, you must call the appropriate model methods in order to modify the data property. Modifying a data property directly without calling the appropriate model method may cause inconsistencies or undefined behavior.

For node data, the model methods are Model.setCategoryForNodeData, Model.setKeyForNodeData, GraphLinksModel.setGroupKeyForNodeData, TreeModel.setParentKeyForNodeData, and TreeModel.setParentLinkCategoryForNodeData. For link data, the model methods are GraphLinksModel.setCategoryForLinkData, GraphLinksModel.setFromKeyForLinkData, GraphLinksModel.setFromPortIdForLinkData, GraphLinksModel.setToKeyForLinkData, GraphLinksModel.setToPortIdForLinkData, and GraphLinksModel.setLabelKeysForLinkData.

This example changes the "to" property of a link data, causing the link to connect to a different node.

  diagram.nodeTemplate =
    $(go.Node, "Auto",
      { locationSpot: go.Spot.Center },
      $(go.Shape, "RoundedRectangle",
        { fill: "yellow", stroke: "orange", strokeWidth: 2 }),
      $(go.TextBlock,
        { margin: 5 },
        new go.Binding("text", "key"))
    );

  var nodeDataArray = [
    { key: "Alpha" },
    { key: "Beta" },
    { key: "Gamma" }
  ];
  var linkDataArray = [
    { from: "Alpha", to: "Beta" }
  ];
  diagram.model = new go.GraphLinksModel(nodeDataArray, linkDataArray);

  function switchTo() {
    var model = diagram.model;
    // all model changes should happen in a transaction
    model.startTransaction("reconnect link");
    var data = model.linkDataArray[0];  // get the first link data
    if (model.getToKeyForLinkData(data) === "Beta")
      model.setToKeyForLinkData(data, "Gamma");
    else
      model.setToKeyForLinkData(data, "Beta");
    model.commitTransaction("reconnect link");
  }
  function loop() {
    setTimeout(function() { switchTo(); loop(); }, 1000);
  }
  loop();

Binding to GraphObject sources

The binding source object need not be a plain JavaScript data object held in the diagram's model. The source object may instead be a named GraphObject in the same Part. The source property must be a settable property of the class. The binding is evaluated when the property is set to a new value.

One common use of such a binding is to change the appearance of a Part when the Part.isSelected. Call Binding.ofObject to cause the Binding to use the object whose GraphObject.name is the given name. Use the empty string, "", or no argument, to refer to the whole Part itself. This is a convenience so that you do not need to name the whole Part. "ofObject" really means "of the GraphObject named ...", as found by Panel.findObject when there is a string argument.

In the example below, the Shape.fill is bound to the Part.isSelected property. When the node is selected or de-selected, the Part.isSelected property changes value, so the binding is evaluated. The conversion function gets a boolean value and returns the desired brush color to be used as the shape's fill. This example also turns off selection adornments, so that the only visual way to tell that a node is selected is by the shape's fill color.

  diagram.nodeTemplate =
    $(go.Node, "Auto",
      { selectionAdorned: false },  // no blue selection handle!
      $(go.Shape, "RoundedRectangle",
        { fill: "white" },
        // bind Shape.fill to Part.isSelected converted to a color
        new go.Binding("fill", "isSelected", function(sel) {
              return sel ? "dodgerblue" : "lightgray";
            }).ofObject()),  // no name means bind to the whole Part
      $(go.TextBlock,
        { margin: 5 },
        new go.Binding("text", "descr"))
    );

  diagram.model.nodeDataArray = [
    { descr: "Select me!" },
    { descr: "I turn blue when selected." }
  ];

Caution: do not declare cycles of binding dependencies -- that will result in undefined behavior. GraphObject binding sources also require the Part to be bound to data (i.e. Part.data must be non-null). The property on the GraphObject must be settable, so it does not work on read-only properties such as ones that return computed values (e.g. Part.isTopLevel) or Iterators (e.g. Node.linksConnected).

Binding to the shared Model.modelData source

The binding source object may be a third kind of source, besides the Panel.data or some GraphObject within the panel. It can also be the JavaScript Object that is the shared Model.modelData object. This permits binding of Node or Link element properties to shared properties in the model that will exist and may be modified even though no nodes or links exist in the model.

In the example below, the Shape.fill is bound to the "color" property on the Model.modelData object. As you click the button the changeColor function modifies the modelData object by calling Model.setDataProperty.

diagram.nodeTemplate =
  $(go.Node, "Auto",
    $(go.Shape, "RoundedRectangle",
      { fill: "white" },  // the default value if there is no modelData.color property
      new go.Binding("fill", "color").ofModel()),  // meaning a property of Model.modelData
    $(go.TextBlock,
      { margin: 5 },
      new go.Binding("text"))
  );

// start all nodes yellow
diagram.model.modelData.color = "yellow";

diagram.model.nodeDataArray = [
  { text: "Alpha" },
  { text: "Beta" }
];

diagram.undoManager.isEnabled = true;

changeColor = function() {
  var model = diagram.model;
  diagram.startTransaction();
  // alternate between lightblue and lightgreen colors
  var oldcolor = model.modelData.color;
  var newcolor = (oldcolor === "lightblue" ? "lightgreen" : "lightblue");
  model.setDataProperty(model.modelData, "color", newcolor);
  diagram.commitTransaction("changed shared color");
}

Two-way data binding

All of the bindings above only transfer values from the source data to target properties. But sometimes you would like to be able to transfer values from GraphObjects back to the model data, to keep the model data up-to-date with the diagram. This is possible by using a TwoWay Binding, which can pass values not only from source to target, but also from the target object back to the source data.

  diagram.nodeTemplate =
    $(go.Node, "Auto",
      { locationSpot: go.Spot.Center },
      new go.Binding("location", "loc").makeTwoWay(),  // TwoWay Binding
      $(go.Shape, "RoundedRectangle",
        { fill: "lightblue", stroke: "blue", strokeWidth: 2 }),
      $(go.TextBlock,
        { margin: 5 },
        new go.Binding("text", "key"))
    );

  var nodeDataArray = [
    { key: "Alpha", loc: new go.Point(0, 0) }
  ];
  diagram.model = new go.GraphLinksModel(nodeDataArray);

  shiftNode = (function() {  // define a function named "shiftNode" callable by onclick
    // all model changes should happen in a transaction
    diagram.startTransaction("shift node");
    var data = diagram.model.nodeDataArray[0];  // get the first node data
    var node = diagram.findNodeForData(data);   // find the corresponding Node
    var p = node.location.copy();  // make a copy of the location, a Point
    p.x += 10;
    if (p.x > 200) p.x = 0;
    // changing the Node.location also changes the data.loc property due to TwoWay binding
    node.location = p;
    // show the updated location held by the "loc" property of the node data
    document.getElementById("bindTwoWayData").textContent = data.loc.toString();
    diagram.commitTransaction("shift node");
  });
  shiftNode();  // initialize everything

Click on the button to move the Node. The effect is basically what happens when the user drags the node. In this example, the TwoWay Binding on Node.location will update the "loc" property of the node data that is the Node's Part.data.

nodedata.loc:

Just as you can use a conversion function when going from source to target, you can supply a conversion function to Binding.makeTwoWay for going from target to source. For example, to represent the location as a string in the model data instead of as a Point:

// storage representation of Points/Sizes/Rects/Margins/Spots is as strings, not objects:
new go.Binding("location", "loc", go.Point.parse).makeTwoWay(go.Point.stringify)

However, you must not have a TwoWay binding on the node data property that is the "key" property. (That defaults to the name "key" but is actually the value of Model.nodeKeyProperty.) That property value must always be unique among all node data within the model and is known by the Model. A TwoWay binding might change the value, causing a multitude of problems. Similarly, the Node.key property is read-only, to prevent accidental changes of the key value.

Reasons for TwoWay Bindings

The basic reason for using a TwoWay Binding on a settable property is to make sure that any changes to that property will be copied to the corresponding model data. By making sure that the Model is up-to-date, you can easily "save the diagram" just by saving the model and "loading a diagram" is just a matter of loading a model into memory and setting Diagram.model. If you are careful to only hold JSON-serializable data in the model data, you can just use the Model.toJson and Model.fromJson methods for converting a model to and from a textual representation.

Most bindings do not need to be TwoWay. For performance reasons you should not make a Binding be TwoWay unless you actually need to propagate changes back to the data. Most settable properties are only set on initialization and then never change.

Settable properties only change value when some code sets them. That code might be in code that you write as part of your app. Or it might be in a command (see Commands) or a tool (see Tools). Here is a list of properties for which a TwoWay Binding is plausible because one of the predefined commands or tools modify them:

You will not need to use a TwoWay binding on a property if the Tool that modifies it cannot run, or if the command that modifies it cannot be invoked. You probably will not need a TwoWay binding on any other properties unless you write code to modify them. And even then it is sometimes better to write the code to modify the model data directly by calling Model.setDataProperty, depending on a OneWay Binding to update the GraphObject property.

It is also possible to use TwoWay Bindings where the source is a GraphObject rather than model data. This is needed less frequently, when you do not want to have the state stored in the model, but you do want to synchronize properties of GraphObjects within the same Part. Use TwoWay Bindings sparingly.