简体   繁体   中英

How to set the key value on a Go.js Node to create links

I'm using Go.js to create a canvas a user can draw straight lines on. From the documentation, I've been able to create nodes. Node creation code looks like:

const node = this.goMake(go.Node, 'Horizontal',
    { position: new go.Point(point[0], point[1]) },  // set the Node.position
        this.goMake(go.Shape, 'Circle', { width: 10, height: 10, fill: 'lightblue' })
);

As I understand the documentation, in order to create a line (non-directional link) between the two nodes, I need to use their key values like so:

this.myDiagram.model.addLinkData({ from: node1.key, to: node2.key });

When logging out my nodes, I see that key value is an empty string.

Question: When creating my nodes using the first snippet above, how do I inject the key value so the second code snippet properly links the two? Creating unique values for all points is not an issue, I just can't figure out how to attach the unique value to the node's key property.

keys are a property of Model data, where the model has an array of node data and link data. Keys are not properties of the Nodes themselves exactly. node.key is just a convenience for node.data.key .

So when you write:

myDiagram.model.addNodeData( { key: 'a' });

It is making a copy of the myDiagram.nodeTemplate, and assigning that Node the node.data of { key: 'a' } , so that node's key is 'a'

In other words, you can only relate these things by the model, not by the Node that you are creating.

If you are using models, you should be creating node templates on the Diagram, not stand-alone nodes, as it appears you are doing. So something like:

myDiagram.nodeTemplate = this.goMake(go.Node, 'Horizontal',
    { position: new go.Point(point[0], point[1]) },  // set the Node.position
        this.goMake(go.Shape, 'Circle', { width: 10, height: 10, fill: 'lightblue' })
);

or if you have multiple templates:

myDiagram.nodeTemplateMap.add('newTemplate', this.goMake(go.Node, 'Horizontal',
    { position: new go.Point(point[0], point[1]) },  // set the Node.position
        this.goMake(go.Shape, 'Circle', { width: 10, height: 10, fill: 'lightblue' })
));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM