editor.graph.model.cells stops working after deleting shapes

Viewed 48

I've started adding a new feature to my instance of GraphEditor to validate diagrams. The idea is this will involve performing operations such as ensuring there is one start event per diagram and that all starts have at least one end event. The following from my function should check that that the diagram has a start event, and if not, display a message:

EditorUi.prototype.validate = function() {
  var graph = this.editor.graph;


  var vertexes = [];
  var startEvents = [];

  var i = 0;

  while (graph.model.cells[i] != null) {
    if (graph.model.cells[i].vertex) {
      vertexes.push(graph.model.cells[i]);
    }
    i++;
  }

  for (i = 0; i < vertexes.length; i++) {
    if (vertexes[i].style.includes('outline=standard')) {
      startEvents.push(vertexes[i]);
    }
  }

  if (startEvents.length < 1) {
    alert('Your design is missing a start event!');
  }
};

It works... Until you try deleting a shape. After deleting a shape, the function doesn't pick up any newly-added shapes - the while loop on graph.model.cells[i] only gets the cells added up to the point that you deleted the deleted shape. Any shapes added afterwards are not picked up. Any ideas what's going on? Thanks!

1 Answers

So, I discovered my problem lay in a misunderstanding of what I was doing with graph.model.cells[i]. I somehow thought I was iterating by i through some kind of array of cells, when in fact I was getting cells with id of i, meaning if a cell is deleted, it returned null, so my function stopped looking for cells. I found a way of doing what I wanted, which I've given below:

var graph = this.editor.graph;
var cells = [];
var vertexes = [];
var startEvents = [];

cells = graph.model.getDescendants(graph.model.cells[0]);

for (i = 0; i < cells.length; i++) {
  if (cells[i].vertex) {
    vertexes.push(cells[i]);
  }
}

for (i = 0; i < vertexes.length; i++) {
  if (vertexes[i].style.includes('outline=standard')) {
    startEvents.push(vertexes[i]);
  }
}

if (startEvents.length < 1) {
  alert('Your design is missing a start event!');
}

Related