UNPKG

create-gojs-kit

Version:

A CLI for downloading GoJS samples, extensions, and docs

1,039 lines (974 loc) 70.7 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="preconnect" href="https://rsms.me/"> <link rel="stylesheet" href="../assets/css/style.css"> <!-- Copyright 1998-2025 by Northwoods Software Corporation. --> <meta itemprop="name" content="Data Binding" /> <meta property="og:title" content="Data Binding" /> <meta name="twitter:title" content="Data Binding" /> <meta property="og:image" content="https://gojs.net/latest/assets/images/fp/defaultCard.png" /> <meta itemprop="image" content="https://gojs.net/latest/assets/images/fp/defaultCard.png" /> <meta name="twitter:image" content="https://gojs.net/latest/assets/images/fp/defaultCard.png" /> <meta property="og:url" content="https://gojs.net/latest/intro/dataBinding.html" /> <meta property="twitter:url" content="https://gojs.net/latest/intro/dataBinding.html" /> <meta name="twitter:card" content="summary_large_image" /> <meta property="og:type" content="website" /> <meta property="twitter:domain" content="gojs.net" /> <title> Data Binding | GoJS </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 h-[var(--topnav-h)] z-30 bg-white border-b border-b-gray-200"> <div class="max-w-screen-xl mx-auto flex flex-wrap items-start justify-between px-4"> <a class="text-white bg-nwoods-primary font-bold !leading-[calc(var(--topnav-h)_-_1px)] my-0 px-2 text-4xl lg:text-5xl logo" href="../"> GoJS </a> <div class="relative"> <button id="topnavButton" class="h-[calc(var(--topnav-h)_-_1px)] px-2 m-0 text-gray-900 bg-inherit shadow-none md:hidden hover:!bg-inherit hover:!text-nwoods-accent hover:!shadow-none" aria-label="Navigation"> <svg class="h-7 w-7 block" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"> <path d="M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5" stroke-linecap="round" stroke-linejoin="round"/> </svg> </button> <div id="topnavList" class="hidden md:block"> <div class="absolute right-0 z-30 flex flex-col items-end rounded border border-gray-200 p-4 pl-12 shadow bg-white text-gray-900 font-semibold md:flex-row md:space-x-4 md:items-start md:border-0 md:p-0 md:shadow-none md:bg-inherit"> <a href="../learn/">Learn</a> <a href="../samples/">Samples</a> <a href="../intro/">Intro</a> <a href="../api/">API</a> <a href="../download.html">Download</a> <a href="https://forum.nwoods.com/c/gojs/11" target="_blank" rel="noopener">Forum</a> <a id="tc" href="https://nwoods.com/contact.html" target="_blank" rel="noopener" onclick="getOutboundLink('https://nwoods.com/contact.html', 'contact');">Contact</a> <a id="tb" href="https://nwoods.com/sales/index.html" target="_blank" rel="noopener" onclick="getOutboundLink('https://nwoods.com/sales/index.html', 'buy');">Buy</a> </div> </div> </div> </div> </nav> <script> window.addEventListener("DOMContentLoaded", function () { // topnav var topButton = document.getElementById("topnavButton"); var topnavList = document.getElementById("topnavList"); if (topButton && topnavList) { topButton.addEventListener("click", function (e) { topnavList .classList .toggle("hidden"); e.stopPropagation(); }); document.addEventListener("click", function (e) { // if the clicked element isn't the list, close the list if (!topnavList.classList.contains("hidden") && !e.target.closest("#topnavList")) { topButton.click(); } }); // set active <a> element var url = window .location .href .toLowerCase(); var aTags = topnavList.getElementsByTagName('a'); for (var i = 0; i < aTags.length; i++) { var lowerhref = aTags[i] .href .toLowerCase(); if (lowerhref.endsWith('.html')) lowerhref = lowerhref.slice(0, -5); if (url.startsWith(lowerhref)) { aTags[i] .classList .add('active'); break; } } } }); </script> <div class="sticky top-0 left-0 z-10 px-2 w-full bg-white border-b border-b-gray-200 md:hidden"> <button id="sidenavButton" class="flex p-2 text-gray-900 bg-inherit shadow-none items-center text-sm font-semibold hover:!bg-inherit hover:!text-nwoods-accent hover:!shadow-none" aria-label="Navigation"> <svg class="h-7 w-7 block mr-2" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"> <path d="M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5" stroke-linecap="round" stroke-linejoin="round"/> </svg> <span>Menu</span> </button> </div> <script> window.addEventListener("DOMContentLoaded", function () { // sidenav var sideButton = document.getElementById("sidenavButton"); var sidenav = document.getElementById("sidenav"); if (sideButton && sidenav) { sideButton.addEventListener("click", function (e) { sidenav .classList .toggle("hidden"); e.stopPropagation(); }); document.addEventListener("click", function (e) { // if the clicked element isn't the list, close the list if (!sidenav.classList.contains("hidden") && !e.target.closest("#sidenavList")) { sideButton.click(); } }); } }); </script> <div class="flex flex-row md:min-h-screen w-full max-w-screen-xl mx-auto"> <aside id="sidenav" class="hidden fixed top-0 left-0 z-10 w-full bg-black/10 min-h-screen max-h-screen overflow-x-hidden overflow-y-auto shrink-0 md:block md:sticky md:w-52 md:min-h-0 md:bg-inherit md:border-r md:border-r-gray-200 md:overscroll-auto"> <nav id="sidenavList" class="flex flex-col bg-white w-52 min-h-screen pl-2 pt-4 pb-24 md:w-full md:min-h-0"> <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="svelte.html">GoJS with Svelte</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="routers.html">Routers</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="theming.html">Theming</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="accessibility.html">Accessibility</a> <a href="buttons.html">Buttons</a> <a href="permissions.html">Permissions</a> <a href="validation.html">Validation</a> <a href="animation.html">Animation</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="replacingDeleting.html">Replacing and Deleting</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="SVGContext.html">Rendering to SVG</a> <a href="makingSVG.html">Snapshot to SVG</a> <a href="makingImages.html">Diagram Images</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="performance.html">Performance</a> <a href="platforms.html">Platforms</a> <a href="deployment.html">Deployment</a> </nav> </aside> <script> var navList = document.getElementById('sidenavList'); if (navList !== null) { var url = window.location.href; var lindex = url.lastIndexOf('/'); url = url .slice(lindex + 1) .toLowerCase(); var aTags = navList.getElementsByTagName('a'); var currentindex = -1; for (var i = 0; i < aTags.length; i++) { var lowerhref = aTags[i] .href .toLowerCase(); if (lowerhref.indexOf('/' + url) !== -1) { currentindex = i; aTags[i] .classList .add('active'); break; } } } </script> <div class="px-4 pb-16 w-full overflow-hidden prose"> <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 <a>Model</a>. </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> 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> <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> <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.Stretch.Horizontal }, $(go.TextBlock, headerStyle(), // Header: { portId: "HEADER" }, new go.Binding("text", "head")), $(go.Shape, "LineH", { height: 1, stretch: go.Stretch.Fill }), $(go.TextBlock, textStyle(), // Location: { portId: "LOCATION" }, new go.Binding("text", "loc")), $(go.Shape, "LineH", { height: 1, stretch: go.Stretch.Fill }), $(go.TextBlock, textStyle(), // Fill: { portId: "FILL" }, new go.Binding("text", "color")), $(go.Shape, "LineH", { height: 1, stretch: go.Stretch.Fill }), $(go.TextBlock, textStyle(), // Text: { portId: "TEXT" }, new go.Binding("text", "txt")), $(go.Shape, "LineH", { height: 1, stretch: go.Stretch.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.Routing.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.Stretch.Horizontal }, $(go.TextBlock, headerStyle(), { portId: "HEADER", text: "nodeDataArray" }), $(go.Shape, "LineH", { height: 1, stretch: go.Stretch.Fill }), $(go.TextBlock, textStyle(), { portId: "dataNode1", desiredSize: new go.Size(NaN,16) }), $(go.Shape, "LineH", { height: 1, stretch: go.Stretch.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.Curve.Bezier }, new go.Binding("curviness"), $(go.Shape, { stroke: "brown" }), $(go.Shape, { toArrow: "OpenTriangle", stroke: "brown" }) )); diagram.linkTemplateMap.add("Binding", $(go.Link, { curve: go.Curve.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.Curve.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) }) )); const 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 from the data to the GraphObject: </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 a Binding transfers the property value from the data Object to the Picture or TextBlock 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.Stretch.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.Stretch.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.Stretch.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.Curve.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.Curve.Bezier}, $(go.Shape, {strokeWidth: 1.5}), $(go.Shape, {toArrow: "Boomerang"}), $(go.Panel, "Auto", $(go.Shape, "Rectangle", { fill: "white", strokeWidth: 0}), $(go.TextBlock, new go.Binding("text"), {stroke: "black", margin: 3})))); diagram.linkTemplateMap.add("ReferenceLinkNoText", $(go.Link, new go.Binding("curviness"), {curve: go.Curve.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 const 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 = new go.Node("Auto") .add( new go.Shape("RoundedRectangle", { fill: "white" }) .bind("fill", "color"), // shape.fill = data.color new go.TextBlock({ margin: 5 }) .bind("text") // textblock.text = data.key ); diagram.linkTemplate = new go.Link() .add( new go.Shape() .bind("stroke", "color") // shape.stroke = data.color .bind("strokeWidth", "thick"), // shape.strokeWidth = data.thick new go.Shape({ toArrow: "OpenTriangle", fill: null }) .bind("stroke", "color") // shape.stroke = data.color .bind("strokeWidth", "thick") // shape.strokeWidth = data.thick ); const nodeDataArray = [ { key: 1, text: "Alpha", color: "lightblue" }, { key: 2, text: "Beta", color: "pink" } ]; const linkDataArray = [ { from: 1, to: 2, color: "blue", thick: 2 } ]; diagram.model = new go.GraphLinksModel(nodeDataArray, linkDataArray); </code></pre> <script> goCode('simpleModelWithBind', 250, 150); </script> <p> Note that the link template uses two bindings of the source "color" property. There is one for each target <a>Shape</a> in the <a>Link</a> template; each binds the <a>Shape.stroke</a> property, although they could target other properties. </p> <p> Alternatively, using <a>GraphObject.make</a>: </p> <pre class="lang-js"><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")) // textblock.text = data.text ); 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 ); </code></pre> <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 <a>Part.location</a> is of type <a>Point</a>, so in this example the data property value must be an instance of Point. </p> <pre class="lang-js" id="bindLocationPoint"><code> diagram.nodeTemplate = new go.Node("Auto") .bind("location", "loc") // get the Node.location from the data.loc value .add( new go.Shape("RoundedRectangle", { fill: "white" }) .bind("fill", "color"), new go.TextBlock({ margin: 5 }) .bind("text") ); const nodeDataArray = [ // for each node specify the location using Point values { key: 1, text: "Alpha", color: "lightblue", loc: new go.Point(0, 0) }, { key: 2, text: "Beta", color: "pink", loc: new go.Point(100, 50) } ]; const linkDataArray = [ { from: 1, to: 2 } ]; 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 = new go.Node("Auto") .bind("location", "loc", go.Point.parse) // convert string into a Point value .add( new go.Shape("RoundedRectangle", { fill: "white" }) .bind("fill", "color"), new go.TextBlock({ margin: 5 }) .bind("text") ); const nodeDataArray = [ { key: 1, text: "Alpha", color: "lightblue", loc: "0 0" }, // note string values for location { key: 2, text: "Beta", color: "pink", loc: "100 50" } ]; const linkDataArray = [ { from: 1, to: 2 } ]; 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 = new go.Node("Auto") .bind("location", "loc", go.Point.parse) .add( new go.Shape("RoundedRectangle", { // default values if the data.highlight is undefined: fill: "yellow", stroke: "orange", strokeWidth: 2 }) .bind("fill", "highlight", v => v ? "pink" : "lightblue") .bind("stroke", "highlight", v => v ? "red" : "blue") .bind("strokeWidth", "highlight", v => v ? 3 : 1), new go.TextBlock({ margin: 5 }) .bind("text") ); const nodeDataArray = [ { key: 1, text: "Alpha", loc: "0 0", highlight: false }, { key: 2, text: "Beta", loc: "100 50", highlight: true }, { key: 3, text: "Gamma", loc: "0 100" } // highlight property undefined: use defaults ]; const linkDataArray = [ { from: 1, to: 2 } ]; 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 (see <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.set</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 = new go.Node("Auto", { locationSpot: go.Spot.Center }) .add( new go.Shape("RoundedRectangle", { // default values if the data.highlight is undefined: fill: "yellow", stroke: "orange", strokeWidth: 2 }) .bind("fill", "highlight", v => v ? "pink" : "lightblue") .bind("stroke", "highlight", v => v ? "red" : "blue") .bind("strokeWidth", "highlight", v => v ? 3 : 1), new go.TextBlock({ margin: 5 }) .bind("text") ); diagram.model.nodeDataArray = [ { text: "Alpha", highlight: false } // just one node, and no links ]; function flash() { // all model changes should happen in a transaction diagram.model.commit(m => { const data = m.nodeDataArray[0]; // get the first node data m.set(data, "highlight", !data.highlight); }, "flash"); } function loop() { setTimeout(() => { flash(); loop