Dynamically changing layout types

I have some code that lays out an initial diagram using a digraph layout and it works fine. I then allow a user to change the diagraph layout to a force directed layout using this code:

diagram.layout = new go.ForceDirectedLayout();

And this code works fine and the diagram changes to a force directed layout. But I also let the user change it back to a digraph layout using this code:

diagram.layout = new go.LayeredDigraphLayout();

This code does not work - the diagram never turns back into a digraph layout. Any idea why it would work one direction but not the other?


I just tried modifying an existing sample to do what you are talking
about, Concept

I added this function:

function toggleLayout() { var $ = go.GraphObject.make; if (myDiagram.layout instanceof go.ForceDirectedLayout) { myDiagram.layout = $(go.LayeredDigraphLayout, { direction: 90 }); } else { myDiagram.layout = $(go.ForceDirectedLayout, { defaultSpringLength: 30, defaultElectricalCharge: 100 }); } }
and then I added a Button:

<button onclick="toggleLayout()">Toggle Layout</button>

And everything seems to work just the way you are expecting. So I’m wondering what else is different in your app.

At this point I’ve got nothing. I made some changes based on what you had here and my results went downhill. When starting from a LayeredDigraphLayout, when I make this call:
workItemDiagram.layout = new go.ForceDirectedLayout();
the diagram does change to a force directed. However, I changed it to match the code posted:
function setForceDiagram() {
var $ = go.GraphObject.make;
workItemDiagram.Layout = $(go.ForceDirectedLayout,
defaultSpringLength: 30,
defaultElectricalCharge: 100
And now it doesn’t change to a force directed at all. It still doesn’t switch back and the code is being hit and called.

Any other thoughts on where I can look?


You capitalized “Layout”, but all properties (other than constants) in GoJS start with a lower case letter.

Using go.GraphObject.make to initialize properties helps catch typos because it checks for correctly spelled property names. But you cannot use go.GraphObject.make to modify existing objects.

Sigh. It was just that simple. Thanks Walter - I completely missed that somehow.

In the next release if you use go-debug.js we’ll throw an Error if you try setting Diagram.Layout instead of setting Diagram.layout. (But if you use go.js, we won’t detect that.)