UNPKG

gojs

Version:

Interactive diagrams, charts, and graphs, such as trees, flowcharts, orgcharts, UML, BPMN, or business diagrams

974 lines (913 loc) 64.8 kB
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no, viewport-fit=cover"/> <link rel="stylesheet" href="../assets/css/style.css"/> <!-- Copyright 1998-2023 by Northwoods Software Corporation. --> <title> GoJS Data Binding -- Northwoods Software </title> <link rel="stylesheet" href="../assets/css/prism.css" /> </head> <script> window.diagrams = []; window.goCode = function(pre, w, h, parentid, animation) { window.diagrams.push([pre, w, h, parentid, animation]); } </script> <body> <nav id="navTop" class="w-full z-30 top-0 text-white bg-nwoods-primary"> <div class="w-full container max-w-screen-lg mx-auto flex flex-wrap sm:flex-nowrap items-center justify-between mt-0 py-2"> <div class="md:pl-4"> <a class="text-white hover:text-white no-underline hover:no-underline font-bold text-2xl lg:text-4xl rounded-lg hover:bg-nwoods-secondary " href="../"> <h1 class="my-0 p-1 ">GoJS</h1> </a> </div> <button id="topnavButton" class="rounded-lg sm:hidden focus:outline-none focus:ring" aria-label="Navigation"> <svg fill="currentColor" viewBox="0 0 20 20" class="w-6 h-6"> <path id="topnavOpen" fill-rule="evenodd" d="M3 5a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 10a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM9 15a1 1 0 011-1h6a1 1 0 110 2h-6a1 1 0 01-1-1z" clip-rule="evenodd"></path> <path id="topnavClosed" class="hidden" fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd"></path> </svg> </button> <div id="topnavList" class="hidden sm:block items-center w-auto mt-0 text-white p-0 z-20"> <ul class="list-reset list-none font-semibold flex justify-end flex-wrap sm:flex-nowrap items-center px-0 pb-0"> <li class="p-1 sm:p-0"><a class="topnav-link" href="../learn/">Learn</a></li> <li class="p-1 sm:p-0"><a class="topnav-link" href="../samples/">Samples</a></li> <li class="p-1 sm:p-0"><a class="topnav-link" href="../intro/">Intro</a></li> <li class="p-1 sm:p-0"><a class="topnav-link" href="../api/">API</a></li> <li class="p-1 sm:p-0"><a class="topnav-link" href="https://www.nwoods.com/products/register.html">Register</a></li> <li class="p-1 sm:p-0"><a class="topnav-link" href="../download.html">Download</a></li> <li class="p-1 sm:p-0"><a class="topnav-link" href="https://forum.nwoods.com/c/gojs/11">Forum</a></li> <li class="p-1 sm:p-0"><a class="topnav-link" href="https://www.nwoods.com/contact.html" target="_blank" rel="noopener" onclick="getOutboundLink('https://www.nwoods.com/contact.html', 'contact');">Contact</a></li> <li class="p-1 sm:p-0"><a class="topnav-link" href="https://www.nwoods.com/sales/index.html" target="_blank" rel="noopener" onclick="getOutboundLink('https://www.nwoods.com/sales/index.html', 'buy');">Buy</a></li> </ul> </div> </div> <hr class="border-b border-gray-600 opacity-50 my-0 py-0" /> </nav> <div class="md:flex flex-col md:flex-row md:min-h-screen w-full max-w-screen-xl mx-auto"> <div id="navSide" class="flex flex-col w-full md:w-40 lg:w-48 text-gray-700 bg-white flex-shrink-0"> <div class="flex-shrink-0 px-8 py-4"> <button id="navButton" class="rounded-lg md:hidden focus:outline-none focus:ring" aria-label="Navigation"> <svg fill="currentColor" viewBox="0 0 20 20" class="w-6 h-6"> <path id="navOpen" fill-rule="evenodd" d="M3 5a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 10a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM9 15a1 1 0 011-1h6a1 1 0 110 2h-6a1 1 0 01-1-1z" clip-rule="evenodd"></path> <path id="navClosed" class="hidden" fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd"></path> </svg> </button> </div> <nav id="navList" class="min-h-screen hidden md:block sidebar-nav flex-grow px-1 lg:px-4 pb-4 md:pb-0 md:overflow-y-auto break-words"> <a href="index.html">Basics</a> <a href="buildingObjects.html">Building Parts</a> <a href="usingModels.html">Using Models</a> <a href="dataBinding.html">Data Binding</a> <a href="react.html">GoJS with React</a> <a href="angular.html">GoJS with Angular</a> <a href="textBlocks.html">TextBlocks</a> <a href="shapes.html">Shapes</a> <a href="pictures.html">Pictures</a> <a href="panels.html">Panels</a> <a href="tablePanels.html">Table Panels</a> <a href="brush.html">Brushes</a> <a href="sizing.html">Sizing Objects</a> <a href="itemArrays.html">Item Arrays</a> <a href="changedEvents.html">Changed Events</a> <a href="transactions.html">Transactions</a> <a href="viewport.html">Coordinates</a> <a href="initialView.html">Initial View</a> <a href="collections.html">Collections</a> <a href="links.html">Links</a> <a href="linkLabels.html">Link Labels</a> <a href="connectionPoints.html">Link Points</a> <a href="ports.html">Ports</a> <a href="nodes.html">Nodes</a> <a href="typings.html">Typings</a> <a href="debugging.html">Debugging</a> <a href="layouts.html">Layouts</a> <a href="trees.html">Trees</a> <a href="subtrees.html">SubTrees</a> <a href="groups.html">Groups</a> <a href="subgraphs.html">SubGraphs</a> <a href="sizedGroups.html">Sized Groups</a> <a href="selection.html">Selection</a> <a href="highlighting.html">Highlighting</a> <a href="animation.html">Animation</a> <a href="toolTips.html">ToolTips</a> <a href="contextmenus.html">Context Menus</a> <a href="events.html">Diagram Events</a> <a href="tools.html">Tools</a> <a href="commands.html">Commands</a> <a href="permissions.html">Permissions</a> <a href="validation.html">Validation</a> <a href="HTMLInteraction.html">HTML Interaction</a> <a href="layers.html">Layers &amp; Z-ordering</a> <a href="palette.html">Palette</a> <a href="overview.html">Overview</a> <a href="resizing.html">Resizing Diagrams</a> <a href="replacingDeleting.html">Replacing and Deleting</a> <a href="buttons.html">Buttons</a> <a href="templateMaps.html">Template Maps</a> <a href="legends.html">Legends and Titles</a> <a href="extensions.html">Extensions</a> <a href="geometry.html">Geometry Strings</a> <a href="grids.html">Grid Patterns</a> <a href="graduatedPanels.html">Graduated Panels</a> <a href="makingImages.html">Diagram Images</a> <a href="makingSVG.html">Diagram SVG</a> <a href="printing.html">Printing</a> <a href="serverSideImages.html">Server-side Images</a> <a href="nodeScript.html">GoJS in Node.js</a> <a href="testing.html">Testing</a> <a href="storage.html">Storage</a> <a href="performance.html">Performance</a> <a href="source.html">Building from Source</a> <a href="platforms.html">Platforms</a> <a href="deployment.html">Deployment</a> </nav> </div> <div class="pt-4 px-2 md:px-0 lg:px-4 pb-16 w-full overflow-hidden"> <h1>Data Binding</h1> <p> 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 <a>GraphObject</a>s; the source objects are usually JavaScript data objects held in a model. </p> <p> You could write code that gets a desired value from the model data, searches the <a>Diagram</a> for the appropriate <a>Part</a>, searches for the target <a>GraphObject</a> 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 <a>Binding</a> that names the properties on the source object and on the target object. </p> <p> Trying to bind a non-existent property of a <a>GraphObject</a> 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. </p> <p> Data bindings are used to keep <a>GraphObject</a> properties in sync with their <a>Part</a>'s data's properties. They are not used to establish or maintain relationships between Parts. Each kind of <a>Model</a> has its own methods for declaring the relationships between parts. </p> <h2 id="RelationshipsOfPartsAndDataAndBinding">The Relationships of Parts and Data and Binding</h2> <p> First, look at a diagram that includes comments about the GraphObjects used to build some example nodes and links: </p> <pre class="lang-js" id="commented" style="display:none"><code> diagram.nodeTemplate = $(go.Node, "Auto", { scale : 1.6, isShadowed: true }, new go.Binding("location", "pos", go.Point.parse), { locationSpot: go.Spot.Center, portId: "NODE" }, $(go.Shape, "RoundedRectangle", { fill: "white", portId: "SHAPE" }, new go.Binding("fill", "color")), $(go.TextBlock, { margin: 4, portId: "TEXTBLOCK" }, new go.Binding("text", "txt")) ); diagram.linkTemplate = $(go.Link, { isShadowed: true }, $(go.Shape, { strokeWidth: 5, stroke: "orange" }) ); // Represents the nodeDataArray for the two nodes diagram.nodeTemplateMap.add("dataNode", $(go.Node, "Auto", { locationSpot: go.Spot.Center, scale: 1.2, selectionAdorned: true, fromSpot: go.Spot.AllSides, toSpot: go.Spot.AllSides, shadowColor: "#C5C1AA" }, new go.Binding("location", "pos", go.Point.parse), $(go.Shape, "Rectangle", { fill: "lightgray" }), $(go.Panel, "Vertical", { defaultStretch: go.GraphObject.Horizontal }, $(go.TextBlock, headerStyle(), // Header: { portId: "HEADER" }, new go.Binding("text", "head")), $(go.Shape, "LineH", { height: 1, stretch: go.GraphObject.Fill }), $(go.TextBlock, textStyle(), // Location: { portId: "LOCATION" }, new go.Binding("text", "loc")), $(go.Shape, "LineH", { height: 1, stretch: go.GraphObject.Fill }), $(go.TextBlock, textStyle(), // Fill: { portId: "FILL" }, new go.Binding("text", "color")), $(go.Shape, "LineH", { height: 1, stretch: go.GraphObject.Fill }), $(go.TextBlock, textStyle(), // Text: { portId: "TEXT" }, new go.Binding("text", "txt")), $(go.Shape, "LineH", { height: 1, stretch: go.GraphObject.Fill }), $(go.TextBlock, textStyle(), // Text: { portId: "PARENT" }, new go.Binding("text", "parent")) ) ) ); diagram.linkTemplateMap.add("dataNode", // Links from dataNode to Nodes $(go.Link, { routing: go.Link.Orthogonal, corner: 5 }, $(go.Shape, { stroke: "gray", strokeWidth: 2 }), $(go.Shape, { toArrow: "Standard", stroke: "gray", fill: "gray" }) )); diagram.nodeTemplateMap.add("title", $(go.Node, "Auto", new go.Binding("location", "pos", go.Point.parse), $(go.TextBlock, { font: "bold 25pt sans-serif", textAlign: "center"}, new go.Binding("text", "txt")) )); diagram.nodeTemplateMap.add("nodeDataArray", $(go.Node, "Auto", { locationSpot: go.Spot.Center, scale: 1.2, selectionAdorned: true, fromSpot: go.Spot.AllSides, toSpot: go.Spot.AllSides, shadowColor: "#C5C1AA" }, new go.Binding("location", "pos", go.Point.parse), $(go.Shape, "Rectangle", { fill: "lightgray" }), $(go.Panel, "Vertical", { defaultStretch: go.GraphObject.Horizontal }, $(go.TextBlock, headerStyle(), { portId: "HEADER", text: "nodeDataArray" }), $(go.Shape, "LineH", { height: 1, stretch: go.GraphObject.Fill }), $(go.TextBlock, textStyle(), { portId: "dataNode1", desiredSize: new go.Size(NaN,16) }), $(go.Shape, "LineH", { height: 1, stretch: go.GraphObject.Fill }), $(go.TextBlock, textStyle(), { portId: "dataNode2", desiredSize: new go.Size(NaN,16) }) ) )); // Comments diagram.nodeTemplateMap.add("Comment", // Template for comment node $(go.Node, new go.Binding("location", "pos", go.Point.parse), { locationSpot: go.Spot.Center}, $(go.TextBlock, { stroke: "brown", textAlign: "center" }, new go.Binding("text", "txt"), new go.Binding("font", "bold", b => b ? "bold 10pt sans-serif" : "10pt sans-serif")) )); diagram.nodeTemplateMap.add("LinkLabel", // Template for comments on links $(go.Node, new go.Binding("segmentIndex"), new go.Binding("segmentOffset") )); diagram.linkTemplateMap.add("Comment", // Template for links from comments $(go.Link, { curve: go.Link.Bezier }, new go.Binding("curviness"), $(go.Shape, { stroke: "brown" }), $(go.Shape, { toArrow: "OpenTriangle", stroke: "brown" }) )); diagram.linkTemplateMap.add("Binding", $(go.Link, { curve: go.Link.Bezier }, new go.Binding("curviness"), $(go.Shape, { stroke: "green" , strokeWidth: 2, strokeDashArray: [10, 10] }), $(go.Shape, { toArrow: "OpenTriangle", stroke: "green", strokeWidth: 2 }) )); diagram.linkTemplateMap.add("Data", $(go.Link, { curve: go.Link.Bezier }, new go.Binding("curviness"), $(go.Shape, { stroke: "gray" , strokeWidth: 2 }), $(go.Shape, { toArrow: "Standard", fill: "gray", stroke: "gray", strokeWidth: 2 }), $(go.TextBlock, ".data", { font: "bold 12pt Courier", segmentOffset: new go.Point(0, -10) }) )); var model = new go.GraphLinksModel(); model.linkFromPortIdProperty = "fPID"; model.linkToPortIdProperty = "tPID" model.linkLabelKeysProperty = "labels"; model.nodeDataArray = [ { key: 1, txt: "Alpha", color: "lightblue", pos: "50 20"}, { key: 2, txt: "Beta", color: "lightgreen", pos: "50 270"}, { key: 3, category: "dataNode", pos: "300 66", head: "key: 1", txt: "text: Alpha", color: "color: lightblue", loc: "location: 50 0", parent: "parent: null"}, { key: 4, category: "dataNode", pos: "300 316", head: "key: 2", txt: "text: Beta", color: "color: lightgreen", loc: "location: 50 250", parent: "parent: 1"}, { key: 5, category: "nodeDataArray", pos: "500 125"}, { key: 6, category: "title", pos: "320 -100", txt: "TreeModel,\n data"}, { key: 7, category: "title", pos: "-50 -100", txt: "Diagram,\nNodes, Links"}, { key: -1, category: "Comment", pos: "310 190", txt: "These two\ndata Objects are\nare held in the\nnodeDataArray."}, { key: -2, category: "Comment", pos: "100 100", txt: "a Link", bold: true}, { key: -21, category: "LinkLabel"}, { key: -3, category: "Comment", pos: "0 130", txt: "two Nodes", bold: true}, { key: -4, category: "Comment", pos: "190 180", txt: "data binding", bold: true}, { key: -41, category: "LinkLabel", segmentOffset: new go.Point(45, 0)}, { key: -42, category: "LinkLabel", segmentOffset: new go.Point(20, 0)}, { key: -43, category: "LinkLabel", segmentOffset: new go.Point(-10, 0)}, { key: -44, category: "LinkLabel", segmentOffset: new go.Point(25, 0)}, { key: -45, category: "LinkLabel", segmentOffset: new go.Point(20, 0)}, { key: -46, category: "LinkLabel", segmentOffset: new go.Point(-10, 0)} ]; model.linkDataArray = [ { from: 1, to: 2, labels: [-21] }, { from: 1, tPID: "HEADER", to: 3, category: "Data", curviness: 0}, { from: 2, tPID: "HEADER", to: 4, category: "Data", curviness: 0}, { from: -21, tPID: "HEADER", to: 4, category: "Data", curviness: -50}, { from: 5, fPID: "dataNode1", to: 3, tPID: "HEADER", category: "dataNode"}, { from: 5, fPID: "dataNode2", to: 4, tPID: "HEADER", category: "dataNode"}, { from: -1, to: 3, category: "Comment"}, { from: -1, to: 4, category: "Comment"}, { from: -2, to: -21, category: "Comment", curviness: 10}, { from: -3, to: 1, category: "Comment", curviness: 10}, { from: -3, to: 2, category: "Comment", curviness: -10}, { from: -4, to: -41, category: "Comment", curviness: 5}, { from: -4, to: -42, category: "Comment", curviness: 5}, { from: -4, to: -43, category: "Comment", curviness: 5}, { from: -4, to: -44, category: "Comment", curviness: 5}, { from: -4, to: -45, category: "Comment", curviness: 5}, { from: -4, to: -46, category: "Comment", curviness: 5}, { from: -4, to: -47, category: "Comment", curviness: 5}, { from: 3, fPID: "LOCATION", to: 1, tPID: "NODE", category: "Binding", curviness: 10, labels: [-41]}, { from: 3, fPID: "FILL", to: 1, tPID: "SHAPE" , category: "Binding", curviness: 30, labels: [-42]}, { from: 3, fPID: "TEXT", to: 1, tPID: "TEXTBLOCK", category: "Binding", curviness: 50, labels: [-43]}, { from: 4, fPID: "LOCATION", to: 2, tPID: "NODE", category: "Binding", curviness: 10, labels: [-44]}, { from: 4, fPID: "FILL", to: 2, tPID: "SHAPE" , category: "Binding", curviness: 30, labels: [-45]}, { from: 4, fPID: "TEXT", to: 2, tPID: "TEXTBLOCK", category: "Binding", curviness: 50, labels: [-46]} ]; diagram.model = model; // Formatting function headerStyle() { return { margin: 3, font: "bold 12pt sans-serif", minSize: new go.Size(16, 16), maxSize: new go.Size(120, NaN), textAlign: "center" }; } function textStyle() { return { margin: 2, font: "10pt sans-serif", minSize: new go.Size(16, 16), maxSize: new go.Size(120, NaN), textAlign: "center" }; } </code></pre> <script>goCode("commented", 650, 550)</script> <p> The two <a>Node</a>s and one <a>Link</a> belong to the <a>Diagram</a> and are on the left side, with shadows. The <a>TreeModel</a> and the two data objects in its <a>Model.nodeDataArray</a> are on the right side, in gray. </p> <p> Each <a>Node</a> and <a>Link</a> has a <a>Panel.data</a> 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. </p> <p> Each <a>Node</a> also has three <a>Binding</a>s, drawn with dashed green lines: </p> <ul> <li>to the <a>Part.location</a> property from the <code>data.location</code> property</li> <li>to the <a>Shape.fill</a> property from the <code>data.color</code> property</li> <li>to the <a>TextBlock.text</a> property from the <code>data.text</code> property</li> </ul> <p> 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. </p> <p> Note that <a>Binding</a>s are <em>not</em> references from the data to any <a>Part</a>. 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 <a>Diagram.model</a> property and each node or link's <a>Panel.data</a> property. </p> <h3>Item Arrays, Model Data, and Panels</h3> <p> Here's another diagram showing the relationships of data Objects in the model with GraphObjects (Node, Panel, TextBlock, Picture) in the Diagram. The Node is data bound to an Object in the <a>Model.nodeDataArray</a> that has several properties, including one named "items" which is an Array. One of the Panels in the Node has a data binding of the <a>Panel.itemArray</a> property with the source property name being "items". </p> <p> That Array has four Objects in it, each Object having "image" and "name" properties. The <a>Panel.itemTemplate</a> of the Panel whose <a>Panel.itemArray</a> is bound to that Array is defined so as to show a Panel with a RoundedRectangle Shape surrounding a Vertical Panel showing Picture over a TextBlock. </p> <p> The green dashed links show how the Binding transfers the property value from the data Object to the Picture or TextBlock GraphObject in the Node. </p> <pre class="lang-js" id="commented2" style="display:none"><code> //the type that makes up the main visual part of this, which is the file revision map diagram.nodeTemplateMap.add("FileNode", $(go.Node, "Vertical", new go.Binding("location", "position", go.Point.parse), {margin: 20, scale: 1.2, isShadowed: true}, $(go.TextBlock, {margin: 5, shadowVisible: false, font: "bold 11pt sans-serif"}, new go.Binding("text", "key")), $(go.Panel, "Auto", {portId: "TopLeft", toSpot: go.Spot.TopLeft}, $(go.Shape, "RoundedRectangle", {fill: "burlywood", portId: "Rectangle"}), $(go.Panel, "Vertical", new go.Binding("itemArray", "items"), {itemTemplate: $(go.Panel, "Auto", $(go.Shape, "RoundedRectangle", new go.Binding("portId", "port"), {fill: "white", margin: 2, toSpot: go.Spot.Left}), $(go.Panel, "Vertical", {margin: 2}, $(go.Picture, new go.Binding("source", "image", name => "../assets/images/" + name), new go.Binding("portId", "imagePort"), {width: 16, height: 16, margin: 2}), $(go.TextBlock, new go.Binding("text", "name"), new go.Binding("portId", "namePort"), {margin: 2})))})))); //a template for one of the tables that explains the data structure of one of the nodes (for example, Revision 1 or Revision 2) //a mockup of it might look something like the following: /* +-----------------------+ | key: Revision 1 | Clearly, this would be repeated to create tables for each of the revisions. One thing that I would like +----------+------------+ to try is to make yet another itemArray here to practice, where the actual data part of it (that | name | image | displays the name and image for the items) is an itemArray of TableRows. This seems like it should be +----------+------------+ possible, but maybe is somewhat hacky. Oh well, we're doing it anyway. | Folder 1 | folder.png | +----------+------------+ | Folder 2 | folder.png | +----------+------------+ | File 1 | folder.png | +----------+------------+*/ diagram.nodeTemplateMap.add("ItemArrayTable", $(go.Node, "Auto", new go.Binding("location", "position", go.Point.parse), $(go.Shape, "Rectangle", {fill: "#eee", portId: ""}), $(go.Panel, "Auto", {margin: 3, portId: "rightSide", toSpot: go.Spot.Right}, //the outer Rectangle for the whole table $(go.Shape, "Rectangle", {fill: "white"}), $(go.Panel, "Vertical", $(go.Panel, "Auto", {stretch: go.GraphObject.Fill, portId: "itemArrayText", fromSpot: go.Spot.Right}, $(go.Shape, "Rectangle", {fill: "lightgoldenrodyellow", strokeWidth: 0}), $(go.TextBlock, "Item Array", {margin: 2}), ), $(go.Shape, "LineH", {height: 2, stretch: go.GraphObject.Fill}), $(go.Panel, "Table", {defaultRowSeparatorStroke: "gray", defaultColumnSeparatorStroke: "gray", defaultSeparatorPadding: 2}, //default for the header, which shouldn't have a column separator (which covers up the text) $(go.RowColumnDefinition, {row: 0, background: "lightgray", separatorStrokeWidth: 1, separatorStroke: "black"}), $(go.RowColumnDefinition, {row: 1, separatorStrokeWidth: 1, separatorStroke: "black"}), //we need the isPanelMain there to keep the element, according to the itemArray example (https://gojs.net/latest/intro/itemArrays.html) //it looks like only one thing can be the "main" element in the panel, which maybe is something that could be worth addressing later on $(go.Panel, "TableRow", {isPanelMain: true}, $(go.TextBlock, "Index", {column: 0, margin: 2})), new go.Binding("itemArray", "items"), { itemTemplate: $(go.Panel, "TableRow", new go.Binding("portId", "port"), {fromSpot: go.Spot.LeftRightSides}, $(go.TextBlock, new go.Binding("text", "index"), new go.Binding("portId", "index"), {column: 0, margin: 2, fromSpot: go.Spot.Left}))}))))); diagram.nodeTemplateMap.add("NodeDataTable", $(go.Node, "Auto", new go.Binding("location", "position", go.Point.parse), $(go.Shape, "Rectangle", {fill: "#eee"}), $(go.Panel, "Auto", {margin: 3}, $(go.Shape, "Rectangle", {fill: "white"}), $(go.Panel, "Vertical", $(go.Panel, "Auto", {stretch: go.GraphObject.Fill}, $(go.Shape, "Rectangle", {fill: "lightgoldenrodyellow", strokeWidth: 0}), $(go.TextBlock, new go.Binding("text", "name"), {margin: 2})), $(go.Panel, "Table", {defaultRowSeparatorStroke: "gray", defaultColumnSeparatorStroke: "gray", defaultSeparatorPadding: 2}, $(go.RowColumnDefinition, {row: 0, background: "lightgray", separatorStrokeWidth: 1, separatorStroke: "black"}), $(go.RowColumnDefinition, {row: 1, separatorStrokeWidth: 1, separatorStroke: "black"}), $(go.Panel, "TableRow", {isPanelMain: true}, $(go.TextBlock, "Property", {column: 0, margin: 2}), $(go.TextBlock, "Value", {column: 1, margin: 2})), new go.Binding("itemArray", "items"), { itemTemplate: $(go.Panel, "TableRow", new go.Binding("portId", "port"), {fromSpot: go.Spot.LeftRightSides}, $(go.TextBlock, new go.Binding("text", "property"), {column: 0, margin: 2, font: "10pt monospace"}), $(go.TextBlock, new go.Binding("text", "value"), {column: 1, margin: 2}))}))))); //this is intentionally an empty node, because we don't want it to display anything diagram.nodeTemplateMap.add("InvisibleLinkLabel", $(go.Node, new go.Binding("segmentIndex"), new go.Binding("segmentOffset"))); diagram.nodeTemplateMap.add("Comment", $(go.Node, new go.Binding("location", "position", go.Point.parse), $(go.TextBlock, {textAlign: "center", stroke: "brown", fromSpot: go.Spot.Top}, new go.Binding("text", "text"), new go.Binding("desiredSize", "size", go.Size.parse), new go.Binding("portId", "Top")))); diagram.linkTemplateMap.add("BindingLink", $(go.Link, //this is the line itself $(go.Shape, {stroke: "green", strokeWidth: 2, strokeDashArray: [2, 3]}), $(go.Shape, {toArrow: "Boomerang", stroke: "green", fill: "green"}))); diagram.linkTemplateMap.add("Comment", $(go.Link, {curve: go.Link.Bezier, curviness: -30}, $(go.Shape, {stroke: "brown", strokeWidth: 1, strokeDashArray: [3, 3]}), $(go.Shape, {toArrow: "Boomerang", stroke: "brown", fill: "brown"}))); diagram.linkTemplateMap.add("ReferenceLink", $(go.Link, new go.Binding("curviness"), {curve: go.Link.Bezier}, $(go.Shape, {strokeWidth: 1.5}), $(go.Shape, {toArrow: "Boomerang"}), $(go.Panel, "Auto", $(go.Shape, "Rectangle", {fill: "lightskyblue"}), $(go.TextBlock, new go.Binding("text"), {stroke: "black", margin: 3})))); diagram.linkTemplateMap.add("ReferenceLinkNoText", $(go.Link, new go.Binding("curviness"), {curve: go.Link.Bezier}, $(go.Shape, {strokeWidth: 1.5}), $(go.Shape, {toArrow: "Boomerang"}))); diagram.model = new go.GraphLinksModel({ //if it doesn't have this it won't work, courtesy of the dynamic ports example: https://gojs.net/latest/samples/dynamicPorts.html //my understanding is that this is because when the arrays are created (usually), they do so without copying all of the specified data, probably for speed reasons //this could then remove the link data and some "non-essential" properties that we do want to use here //so it turns out that I wasn't doing it the wrong way, which is nice copiesArrays: true, copiesArrayObjects: true, linkFromPortIdProperty: "fromPort", linkToPortIdProperty: "toPort", linkLabelKeysProperty: "keys", nodeDataArray: [ {position: "340 -180", key: "FilesystemNodeDataTable", name: "Node Data", category: "NodeDataTable", items: [ {property: "key", value: "\"Filesystem\""}, {property: "position", value: "\"320 100\""}, {property: "name", value: "\"Filesystem\""}, {property: "category", value: "\"FileNode\""}, {property: "items", port: "itemsPort"}, ]}, //the diagram that we're actually explaining, which is effectively an itemArray with a couple items in it, arranged in a panel {position: "225 40", dataTablePosition: "600 0", key: "Filesystem", name: "Filesystem", category: "FileNode", items: [ {name: "Folder 1", image: "folder.png", dataTablePosition: "375 0", index: "0", port: "Folder1", namePort: "Folder1Name", imagePort: "Folder1Image"}, {name: "Folder 3", image: "folder.png", dataTablePosition: "375 110", index: "1", port: "Folder3", namePort: "Folder3Name", imagePort: "Folder3Image"}, {name: "File 1", image: "document.png", dataTablePosition: "375 220", index: "2", port: "File1", namePort: "File1Name", imagePort: "File1Image"}, {name: "Picture 1", image: "picture.png", dataTablePosition: "375 330", index: "3", port: "Picture1", namePort: "Picture1Name", imagePort: "Picture1Image"}]}, //some more nodes, purely for testing purposes {position: "80 335", size: "150 NaN", key: "Comment1", category: "Comment", text: "Data binding allows text or image source property value to be bound to TextBlock or Picture properties in the itemTemplate panel."}, //set the size to NaN to allow it to only take up the space that it needs, which appears to work! //yay GoJS creators {position: "40 140", size: "150 NaN", key: "Comment2", category: "Comment", text: "Each of the items in the itemArray is displayed according to the itemTemplate, which here is a vertically arranged panel with a Picture and TextBlock." }, {position: "60 -20", size: "150 NaN", key: "Comment3", category: "Comment", text: "The items are displayed in a vertical panel that positions the items and sizes itself." }, {key: "LinkLabel1", category: "InvisibleLinkLabel"}, {key: "LinkLabel2", category: "InvisibleLinkLabel"}, ], linkDataArray: [ //explanation for itemTemplate and the itemArray in general {from: "Comment2", to: "Filesystem", fromPort: "Top", toPort: "Folder1", category: "Comment"}, {from: "Comment2", to: "Filesystem", fromPort: "Top", toPort: "Folder3", category: "Comment"}, {from: "Comment2", to: "Filesystem", fromPort: "Top", toPort: "File1", category: "Comment"}, {from: "Comment2", to: "Filesystem", fromPort: "Top", toPort: "Picture1", category: "Comment"}, //explanation of the base panel {from: "Comment3", to: "Filesystem", toPort: "TopLeft", category: "Comment"}, //to show how the data links work {from: "Filesystem", to: "FilesystemNodeDataTable", category: "ReferenceLink", text: ".data", curviness: 50}, {from: "FilesystemNodeDataTable", to: "FilesystemItemArrayTable", category: "ReferenceLinkNoText", fromPort: "itemsPort", toPort: "itemArrayText"}, //item data information {from: "FilesystemItemArrayTable", fromPort: "Folder1", to: "Folder1ItemDataTable", category: "ReferenceLinkNoText", curviness: 25}, {from: "FilesystemItemArrayTable", fromPort: "Folder3", to: "Folder3ItemDataTable", category: "ReferenceLinkNoText", curviness: 25}, {from: "FilesystemItemArrayTable", fromPort: "File1", to: "File1ItemDataTable", category: "ReferenceLinkNoText", curviness: 25}, {from: "FilesystemItemArrayTable", fromPort: "Picture1", to: "Picture1ItemDataTable", category: "ReferenceLinkNoText", curviness: 25}, //from item data to the respective items {from: "Folder1ItemDataTable", to: "Filesystem", fromPort: "name", toPort: "Folder1Name", category: "BindingLink"}, {from: "Folder1ItemDataTable", to: "Filesystem", fromPort: "image", toPort: "Folder1Image", category: "BindingLink"}, {from: "Folder3ItemDataTable", to: "Filesystem", fromPort: "name", toPort: "Folder3Name", category: "BindingLink"}, {from: "Folder3ItemDataTable", to: "Filesystem", fromPort: "image", toPort: "Folder3Image", category: "BindingLink"}, {from: "File1ItemDataTable", to: "Filesystem", fromPort: "name", toPort: "File1Name", category: "BindingLink"}, {from: "File1ItemDataTable", to: "Filesystem", fromPort: "image", toPort: "File1Image", category: "BindingLink"}, {from: "Picture1ItemDataTable", to: "Filesystem", fromPort: "name", toPort: "Picture1Name", category: "BindingLink", keys: ["LinkLabel1"]}, {from: "Picture1ItemDataTable", to: "Filesystem", fromPort: "image", toPort: "Picture1Image", category: "BindingLink", keys: ["LinkLabel2"]}, //explanation for data binding {from: "Comment1", to: "LinkLabel1", category: "Comment"}, {from: "Comment1", to: "LinkLabel2", category: "Comment"}, ]}); function createNodeItemArrayTable(reference) { //the info table that we're making, blank at this point //the revision that the info table will be of let itemArrayTable = { key: (reference.key + "ItemArrayTable"), name: ("Key: " + reference.key), items: reference.items, port: reference.port, imagePort: (reference.port + "Image"), position: reference.dataTablePosition, category: "ItemArrayTable"}; diagram.model.addNodeData(itemArrayTable); return itemArrayTable; } function createItemDataTable(reference) { //this will create an info table showing all of the properties of an item, similarly to the main node //it is automatic though, so no need to create items let itemDataTable = { items: [ {port: "image", property: "image", value: `\"${reference.image}\"`}, {port: "name", property: "name", value: `\"${reference.name}\"`}, ], name: "Item Data", position: reference.dataTablePosition, category: "NodeDataTable", port: reference.port, key: reference.port + "ItemDataTable"}; diagram.model.addNodeData(itemDataTable); return itemDataTable; } //create all relevant tables var n1 = diagram.model.nodeDataArray[1]; createNodeItemArrayTable(n1); for (let i = 0; i < n1.items.length; i++) createItemDataTable(n1.items[i]); </code></pre> <script>goCode("commented2", 700, 640)</script> <h2 id="BindingStringAndNumberProperties">Binding string and number properties</h2> <p> It is easy to data bind <a>GraphObject</a> properties to data properties. In this example we not only data bind <a>TextBlock.text</a> and <a>Shape.fill</a> in nodes to property values of node data, but for thicker colored lines we also bind <a>Shape.stroke</a> and <a>Shape.strokeWidth</a> in links to property values of link data. </p> <p> All you need to do is add to the target <a>GraphObject</a> a new <a>Binding</a> 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. </p> <pre class="lang-js" id="simpleModelWithBind"><code> 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); </code></pre> <script>goCode("simpleModelWithBind", 250, 150)</script> <p> Note that there are two bindings using the "color" property of the source link data. There is one for each target <a>Shape</a> in the <a>Link</a> template; each binds the <a>Shape.stroke</a> property. </p> <h2 id="BindingObjectPropertiesSuchAsLocation">Binding object properties such as <b>Part.location</b></h2> <p> You can also data bind properties that have values that are objects. For example it is common to data bind the <a>Part.location</a> property. </p> <p> The value of Part.location is a <a>Point</a>, so in this example the data property must be a Point. </p> <pre class="lang-js" id="bindLocationPoint"><code> 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); </code></pre> <script>goCode("bindLocationPoint", 250, 150)</script> <p> For conciseness the rest of these examples make use of the default <a>Diagram.linkTemplate</a>. </p> <h2 id="ConversionFunctions">Conversion functions</h2> <p> But what if you want the data property value for the location to be something other than a <a>Point</a>? You can provide a conversion function that converts the actual data property value to the needed value type or format. </p> <p> For situations like this example, the <a>Point</a> class includes a static function, <a>Point,parse</a>, that you can use to convert a string into a Point object. It expects two numbers to be in the input string, representing the <a>Point.x</a> and <a>Point.y</a> values. It returns a Point object with those values. </p> <p> You can pass a conversion function as the third argument to the <a>Binding</a> constructor. In this case it is <a>Point,parse</a>. This allows the location to be specified in the form of a string ("100 50") rather than as an expression that returns a <a>Point</a>. For data properties on model objects, you will often want to use strings as the representation of <a>Point</a>s, <a>Size</a>s, <a>Rect</a>s, <a>Margin</a>s, and <a>Spot</a>s, 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. </p> <pre class="lang-js" id="bindLocationString"><code> 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); </code></pre> <script>goCode("bindLocationString", 250, 150)</script> <p> 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. </p> <p> Here is an example that has several <a>Shape</a> 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. </p> <pre class="lang-js" id="bindHighlight"><code> 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", v => v ? "pink" : "lightblue"), new go.Binding("stroke", "highlight", v => v ? "red" : "blue"), new go.Binding("strokeWidth", "highlight", v => 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); </code></pre> <script>goCode("bindHighlight", 250, 150)</script> <p class="box bg-danger"> 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 <a>GraphObject.visible</a> or the <a>GraphObject.opacity</a> property. If you really want different visual structures you can use multiple templates (<a href="templateMaps.html">Template Maps</a>). </p> <h2 id="ChangingDataValues">Changing data values</h2> <p> The examples above all depend on the data bindings being evaluated when the <a>Part</a> has been created and its <a>Panel.data</a> property is set to refer to the corresponding node or link data. These actions occur automatically when the <a>Diagram</a> creates diagram parts for the data in the model upon setting <a>Diagram.model</a>. </p> <p> However, <b>GoJS</b> 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. </p> <p> For most data properties, ones that the model does not treat specially but are data-bound, you can just call <a>Model.setDataProperty</a>. In this example we modify the value of "highlight" on a node data object. For fun, this modification occurs about twice a second. </p> <pre class="lang-js" id="changeBoundValue"><code> 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", v => v ? "pink" : "lightblue"), new go.Binding("stroke", "highlight", v => v ? "red" : "blue"), new go.Binding("strokeWidth", "highlight", v => 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() { // all model changes should happen in a transaction diagram.model.commit(m => { var data = m.nodeDataArray[0]; // get the first node data m.set(data, "highlight", !data.highlight); }, "flash"); } function loop() { setTimeout(() => { flash(); loop(); }, 500); } loop(); </code></pre> <script>goCode("changeBoundValue", 250, 150)</script> <h2 id="ChangingGraphStructure">Changing graph structure</h2> <p> Data binding is not used to establish relationships between parts. For data properties that a particular model knows about, such as "to" or "from" for link data in a <a>GraphLinksModel</a>, 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. </p> <p> For node data, the model methods are <a>Model.setCategoryForNodeData</a>, <a>Model.setKeyForNodeData</a>, <a>GraphLinksModel.setGroupKeyForNodeData</a>, <a>TreeModel.setParentKeyForNodeData</a>, and <a>TreeModel.setParentLinkCategoryForNodeData</a>. For link data, the model methods are <a>GraphLinksModel.setCategoryForLinkData</a>, <a>GraphLinksModel.setFromKeyForLinkData</a>, <a>GraphLinksModel.setFromPortIdForLinkData</a>, <a>GraphLinksModel.setToKeyForLinkData</a>, <a>GraphLinksModel.setToPortIdForLinkData</a>, and <a>GraphLinksModel.setLabelKeysForLinkData</a>. </p> <p> This example changes the "to" property of a link data, causing the link to connect to a different node. This example uses the default Link template, which does not have any data bindings. The change in the link relationship is accomplished by calling a model method, not via a data binding. </p> <pre class="lang-js" id="changeLinkTo"><code> 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() { // all model changes should happen in a transaction diagram.model.commit(m => { var data = m.linkDataArray[0]; // get the first link data if (m.getToKeyForLinkData(data) === "Beta") m.setToKeyForLinkData(data, "Gamma"); else m.setToKeyForLinkData(data, "Beta"); }, "reconnect link"); } function loop() { setTimeout(() => { switchTo(); loop(); }, 1000); } loop(); </code></pre> <script>goCode("changeLinkTo", 250, 150)</script> <h2 id="BindingToGraphObjectSources">Binding to <b>GraphObject</b> sources</h2> <p> 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 <a>GraphObject</a> in the same <a>Part</a>. The source property must be a settable property of the class. The binding is evaluated when the property is set to a new value. </p> <p> One common use of such a binding is to change the appearance of a Part when the <a>Part.isSelected</a>. Call <a>Binding.ofObject</a> to cause the Binding to use the object whose <a>GraphObject.name</a> 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 <a>Panel.findObject</a> when there is a string argument. </p> <p> In the example below, the <a>Shape.fill</a> is bound to the <a>Part.isSelected</a> property. When the node is selected or de-selected, the <a>Part.isSelected</a> property changes value, so the binding is evaluated. The conversion function gets a boolean value a